-1

I am new to Swift and Codable approach. I have to decode the following JSON structure, through Codable approach in Swift project.

[
    [
        [
            {
                "id": "58",
                "parentCat": "7",
                "catFirstTitle": "freedom to"
             },
             {
                "id": "40",
                "parentCat": "5",
                "catFirstTitle": "freedom to"
             }
        ],
        [
            {
                "id": "58",
                "parentCat": "7",
                "catFirstTitle": "freedom to"
             },
             {
                "id": "40",
                "parentCat": "5",
                "catFirstTitle": "freedom to"
             }
        ]
    ],
    [
        [
            {
                "id": "58",
                "parentCat": "7",
                "catFirstTitle": "freedom to"
             }
        ]
    ]
]

I could not find any examples of decoding multi level jsonArrays without key names. Any pointer or example will be a great help to me.

pawello2222
  • 46,897
  • 22
  • 145
  • 209
SHS
  • 1,414
  • 4
  • 26
  • 43

1 Answers1

1

You can create a simple struct:

struct Item: Codable {
    let id: String
    let parentCat: String
    let catFirstTitle: String
}

And decode as a nested array object:

let result = try JSONDecoder().decode([[[Item]]].self, from: jsonData)

Note that the result will be of type [[[Item]]].

You may want to flatten it as well:

let flattened = result.flatMap { $0 }.flatMap { $0 }
pawello2222
  • 46,897
  • 22
  • 145
  • 209