Parsing JSON in Swift without array key

1.5k Views Asked by At

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?

1

There are 1 best solutions below

1
On BEST ANSWER

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)