Search code examples
jsonswiftdecodable

Parsing JSON in Swift without array key


I have a JSON-response:

[
    [{
            "id": "1",
            "name": "Toyota",
            "model": "Camry"
        },
        {
            "id": "2",
            "name": "Nissan",
            "model": "Almera"
        }
    ],
    {
        "count": "1234",
        "page": "1"
    }
]

I create decodable model:

struct Car: Decodable {
   var id: String?
   var name: String?
   var model: String?
}

I'm trying extract data like this, for test:

let carsResponse = try JSONDecoder().decode([[Car]].self, from: data)
print(carsResponse[0])

And I have an error:

Expected to decode Array but found a dictionary instead.

What is wrong?


Solution

  • This format is pretty bad, so you'll need to decode the outer container by hand, but it's not difficult:

    struct CarResponse: Decodable {
        var cars: [Car]
    
        init(from decoder: Decoder) throws {
            var container = try decoder.unkeyedContainer()
            cars = try container.decode([Car].self) // Decode just first element
        }
    }
    
    let carsResponse = try JSONDecoder().decode(CarResponse.self, from: data)
    print(carsResponse.cars)