Extract and decode json data using Decodable in swift

swift decode json file
swift combine decode json
swift decode json array
swift parse json array of dictionaries
decodable swift
swift decode nested json
complex json parsing in swift 4
convert data to json swift 4

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


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

JSON Parsing in Swift explained with code examples, JSON Parsing and decoding in Swift is really easy with the default API. Learn how to convert dates, define custom models and parse JSON arrays. Almost every app decodes JSON to show data in a visualized way. Parsing JSON is We can easily decode this by making use of the Decodable protocol: The Decodable protocol was introduced in Swift 4. Since then it has become the standard way for developers to decode JSON received from a remote server. There are tons of tutorials out there that teach you how to utilize the Decodable protocol to decode various types of JSON structure.


Should look something like this:

// MARK: - Root
struct Root: Codable {
    let data: DataClass
}

// MARK: - DataClass
struct DataClass: Codable {
    let custID, type, totalCount: String
    let msgList: [MsgList]
    let categoryCount: String

    enum CodingKeys: String, CodingKey {
        case custID = "custId"
        case type, totalCount, msgList, categoryCount
    }
}

// MARK: - MsgList
struct MsgList: Codable {
    let id, title, subTitle, status: String
}

Then to load your data:

let list: [String : Any] = [:] // load data accordingly...
if let responseMessage = try JSONDecoder().decode(Root.self, from: list)
{
    // responseMessage.data.msgList
}

Class names are just an example, feel free to rename them accordingly.

Decode and Flatten JSON with Dynamic Keys Using Decodable, Decode and Flatten JSON with Dynamic Keys Using Decodable. The Decodable protocol was introduced in Swift 4. Since then it has become the standard way for developers to decode JSON received from a remote server. As you might expect, the overall decoding process works like the reverse of the encoding process: Use JSONSerialization to parse the JSON data to Any. Feed the Any instance to _JSONDecoder. Dispatch to each type’s Decodable initializer to reconstruct a series of Swift instances.


It should be quite easy but you need to decode the full JSON object unless you want to start overriding the init(from decoder:) method and doing some stuff manually.

Trying to pull out just the messages array from the JSON would be more hassle than it's worth.

import UIKit

let jsonData = """
{
   "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"
   }
}
""".data(using: .utf8)

struct Root: Decodable {
    let data: Customer
}

struct Customer: Decodable {
    let custId: String
    let type: String
    let totalCount: String
    let msgList: [Message]
}

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

do {
    let result = try JSONDecoder().decode(Root.self, from: jsonData!)
    print(result)
} catch {
    print(error)
}

You can access the messages like this:

let messages = result.data.msgList

JSON Parsing with Codable in Swift - Flawless iOS, Codable is a type alias for the Encodable and Decodable protocols. Parse JSON data for different types like an object, an array of objects,  It happens sometimes that our JSON data that we would like to decode to Swift objects doesn’t have known properties names and values for particular properties are changing from one entry to another.


You can try

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let str = """

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

        do {

            let res = try JSONDecoder().decode(Root.self, from:Data(str.utf8))

            print(res.list)
        }
        catch {

            print(error)
        }


    }

}

struct Root : Decodable {
    let list : [Message]
    struct AnyCodingKey : CodingKey {
        var stringValue: String
        var intValue: Int?
        init(_ codingKey: CodingKey) {
            self.stringValue = codingKey.stringValue
            self.intValue = codingKey.intValue
        }
        init(stringValue: String) {
            self.stringValue = stringValue
            self.intValue = nil
        }
        init(intValue: Int) {
            self.stringValue = String(intValue)
            self.intValue = intValue
        }
    }
    init(from decoder: Decoder) throws {
        var con = try! decoder.container(keyedBy: AnyCodingKey.self)
        con = try! con.nestedContainer(keyedBy: AnyCodingKey.self, forKey: AnyCodingKey(stringValue:"data"))
        let res = try! con.decode([Message].self, forKey: AnyCodingKey(stringValue:"msgList"))
        self.list = res       
    }
}


struct Message: Codable {
    let id,title,subTitle,status: String? 
}

JSON Parsing with Decodable, Which app does not parse JSON data these days(Firebase based apps maybe). Decoding a JSON response can get pretty intense with all the  JSON Parsing in Swift explained with code examples. JSON parsing in Swift is a common thing to do. Almost every app decodes JSON to show data in a visualized way. Parsing JSON is definitely one of the basics you should learn as an iOS developer. Decoding JSON in Swift is quite easy and does not require any external dependencies.


Parse JSON into struct / object using Decodable protocol, Bless Apple for introducing the Decodable , Encodable, Codable protocol in Swift 4, it makes life as an iOS developer easier phew. An object  If you want to learn more about encoding and decoding in Swift, check out our Saving Data in iOS video course. It covers JSON, Property Lists, XML and much more! I hope you enjoyed this tutorial and if you have any questions or comments, please join the forum discussion below!


JSON Decoding in Swift with Codable: A Practical Guide, Decoding JSON Data is a fundamental part of modern iOS apps. Map the JSON data to your model types by making them conform to the Decodable From an unkeyed container, we can then extract keyed containers for  Decoding JSON having multiple Date formats requires manual implementation of Decodable and of course that means a lot boilerplate code. Swift 5.1 give us new toy called @propertyWrapper. It is additional layer on our properties and we will use it to add transformation layer during JSON decoding process.


Working with JSON and Codable in Swift 5, We will build an iOS app that utilizes a JSON-based API provided by Kiva. already made it easy for developers to fetch and parse JSON data. Decodable and Encodable are the two actual protocols you need to work with. .custom( (Data, Encoder) throws -> Void) To decode it, you can provide JSONDecoder with a decoding strategy:.base64.custom( (Decoder) throws -> Data) Obviously .base64 will be the common choice here, but if you need to do anything custom you can use on of the block-based strategies. Handling URLs. For the most part URLs will work out of the box.