Alberto García
Alberto García

Reputation: 19

Using Decodable to decode array of nested objects

I started working with Decodable some days ago, and I want to know if is it possible to create the model "Car" without create any more model, having this JSON:

{
    "cars": [
        {
            "id": 1,
            "name": "car1"
        },
        {
            "id": 2,
            "name": "car2"
        },
        {
            "id": 3,
            "name": "car3"
        }
    ],
    "pagination": {
        "page": 1,
        "offset": 20
    }
}

The only solution that I found is to create a "wrappwer" model like "Response", containing a property as [Cars].

Can somebody confirm me that is possible to decode this JSON just having the "Car" model?

Thank you.

Best regards

Upvotes: 1

Views: 91

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You can try

    let str = """

        {
        "cars": [
        {
        "id": 1,
        "name": "car1"
        },
        {
        "id": 2,
        "name": "car2"
        },
        {
        "id": 3,
        "name": "car3"
        }
        ],
        "pagination": {
        "page": 1,
        "offset": 20
        }
        }

    """


    do {

        let tr = try JSONSerialization.jsonObject(with: Data(str.utf8), options: []) as! [String:Any] 

        let da = try JSONSerialization.data(withJSONObject: tr["cars"]  , options: [])

        let res = try JSONDecoder().decode([Car].self, from: da)

        print(res)


    }
    catch {

        print(error)
    }

struct Car: Codable {
    let id: Int
    let name: String
}

Upvotes: 1

Related Questions