Search code examples
iosarraysjsonswiftdecode

JSON decoding double nested array in Swift


currently I'm trying to decode JSON with a nested Array. The nested array can have some random numbers of the object inside it. I try to decode it but turns out it return an errors

CodingKeys(stringValue: "itenaries", intValue: nil),
debugDescription : "Expected to decode Array<Any> but found a dictionary 

Sample JSON data

{
   "itenaries": {
      "days":
      [
         [
            {
               "itenary_id":0,
               "itenary_location_name":"Batu Caves Temple"
            }
     
         ],
         [
            {
               "itenary_id":0,
               "itenary_location_name":"KL Tower "
            },
            {
               "itenary_id":1,
               "itenary_location_name":"KL Forest Eco Park"
            }
         ]
      ]
   }
}

My Struct

struct Itenaries : Codable {
    let itenaries : [[Days]]
}

struct Days : Codable {
    let itenary_id : Int
    let itenary_location_name : String
}

Decoding Implementation

let decoder = JSONDecoder()
let itenary = try decoder.decode(Itenaries.self, from: fileData)
print(itenary.itenaries[0][0].itenary_id)

Solution

  • Where do you decode the days key? That's the problem. You need an intermediate struct

    struct Root : Decodable {
        let itenaries : Itenary
    }
    
    struct Itenary : Decodable {
        let days : [[Days]]
    }
    

    ...

    let result = try decoder.decode(Root.self, from: fileData)
    print(result.iternaries.days[0][0].itenary_id)