Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Swift – decode only interested elements

I have a huge json data obtained from HTTP response and I need only a particular portion to be decoded as a model.

{
    "root1": {
        "items": [
            {
                ...
            },
            {
                ...
            },
            {
                ...
            },
            {
                ...
            },
            {
                ...
            }
        ]
    },
    "root2": {
        ...
    },
    "page": {
        "size": 10,
        "totalElements": 5,
        "totalPages": 1,
        "number": 0
    }
}

This is my json template and I do not want to create model for root elements. I am interested only in the items array. Any direct way to decode it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can select what to decode by using a CodingKey enum but you still need to decode from the top/root level.

struct Response: Decodable {
    let root1: Root1

    enum CodingKeys: String, CodingKey {
        case root1
    }
}

struct Root1: Decodable {
    let items: [Item]

    enum CodingKeys: String, CodingKey {
        case items
    }
}

and then the decoding could be done as

var items: [Item] = []
do {
     items = try JSONDecoder().decode(Response.self, from: data).root1.items
} catch {

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading