1

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

3
  • 1
    What is wrong to have the Response containing the array of Car? When you request it, you just have to return the Array of Car. Commented Feb 12, 2019 at 10:27
  • Any change of the standard workflow is expensive and less efficient. Any more model is actually one line of code Commented Feb 12, 2019 at 10:39
  • Thank you for the answers. Then, is much more efficient to have classes even if they have not important data and you don't need it? Commented Feb 16, 2019 at 7:15

1 Answer 1

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.