1

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?

4
  • Your outer array contains an array and a dictionary (with "count" and "page") Commented Dec 8, 2020 at 14:17
  • You ignore count and page. Commented Dec 8, 2020 at 14:22
  • @JoakimDanielson thx. And how i can change my model? Commented Dec 8, 2020 at 14:33
  • You have the correct answer below Commented Dec 8, 2020 at 14:34

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, great, it's work! Thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.