Search code examples
iosarraysjsonswiftjsondecoder

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?


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 {
    
    }