Search code examples
iosjsonswiftdecodable

Extract and decode json data using Decodable in swift


I'm using an external framework for showing message list and detail screen.

Framework internal Message model which we can't modify:

public struct Message: Decodable, Encodable {
    public var id: String?
    public var title: String?
    public var subTitle: String?
    public var status: String?
}

Our API response:

{ 
   "data":{ 
      "custId":"1234",
      "type":"premium",
      "totalCount":"100",
      "msgList":[ 
         { 
            "id":"1",
            "title":"Main Title",
            "subTitle":"Sub title",
            "status":"R"
         },
         { 
            "id":"2",
            "title":"Main Title",
            "subTitle":"Sub title",
            "status":"R"
         }
      ],
      "categoryCount":"50"
   }
}

How I can extract msgList array from JSON response and decode to Message model.

Something like only passing list data/json:

let responseMessage = try JSONDecoder().decode([Message.self], from: list)

Appreciate your help and suggestion!

Thanks


Solution

  • You have to create the payload structure.

    struct Data: Decodable {
        struct Payload: Decodable {
            let msgList: [Message]
        }
    
        let data: Payload
    }
    

    Decode JSON using JSONDecoder.

    let responseMessage = try JSONDecoder().decode([Message.self], from: list)
    

    messageList can access using : responseMessage.data.msgList