How to parse a JSON file use JsonDecoder in swift 5.2 ?

Welcome to this tutorial of coding with appcodezip,  we will learn about decodable.We often use JSON to send and receive data from web services. we will do that easily with Swift. JSON – short for JavaScript Object Notation – may be a way of describing data.




Decodable in swift may be a new way of parsing API in swift. Api parsing in swift is one among the foremost important concepts and with decodable protocol we will parse json api in one line in swift. Decodable protocol are often used with get and post request.

Api parsing in swift has become easy with JsonDecoder class helps you to decode the JSON and map it to a struct or class which inherits from the decodable protocol in swift.

Getting Started With Network Request, URLSession

In this article we are going to learn modern techniques to parse API and make our code more stable and cleaner the api is pretty simple which gives out an employee record.


[{
      "empid": 1,
      "name": "Mr.Sushil Kumar",
      "role": "Developer",
      "org":"AppCodeZip",
      "depid":12755
     },
     {
      "empid": 2,
      "name": "Mr.Sunil Kumar",
      "role": "Developer",
      "org":"AppCodeZip",
      "depid":12756
     }]

Let’s create a single view iOS Application in which we’ll parse the data through JSONDecoder.



Here I have a piece of code.I have an ViewController which is having a function called as getAppcodezipData and inside this function, you can see the code



 func getAppcodezipData()

    {

        let url = "http://demo8044402.mockable.io/appcodezip"


        URLSession.shared.dataTask(with: URL(string: url)!) { (responseData, httpUrlResponse, error) in


            if(error == nil && responseData != nil && responseData?.count != 0)

            {

                //parse the responseData here

                

                

            }


        }.resume()

}



This code over here is if there are no errors and responseData is not nil and count is not equal to zero
I won't be using JSONSerialization but will use JSONDecoder before using JSONDecoder I want to fulfill one requirement as decodable protocol.

I will declaring the response structure EmployeeResponse and structure that inherits from decodable protocol in your API code then swift would try to do internally mapping which is not case-sensitive.


struct EmployeeResponse : Decodable

{

    let empId, depid: Int

    let name, role, org: String


}


JSON Parsing with JSONDecoder-

The rest of the JSON network request are going to be an equivalent for this process. However, we'd like to handle the network response data for the JSONDecoder. No significant changes are needed for this protocol.



import UIKit

struct EmployeResponse : Decodable

{

    let empid, depid: Int

    let name, role, org: String

    

}

class ViewController: UIViewController {


    override func viewDidLoad() {

        super.viewDidLoad()

        getAppcodezipData()

    }


    func getAppcodezipData()

    {

        let url = "http://demo8044402.mockable.io/appcodezip"


        URLSession.shared.dataTask(with: URL(string: url)!) { (responseData, httpUrlResponse, error) in


            if(error == nil && responseData != nil && responseData?.count != 0)

            {

               //parse the responseData here

                let decoder = JSONDecoder()

                do {

                

                    //for json with collection

                    let result = try decoder.decode([EmployeResponse].self, from: responseData!)

                    print(result)


                    for employee in result

                    {

                        print(employee.name)

                    }

                }

                catch let error

                {

                    print("error occured while decoding = \(error.localizedDescription)")


                }

                

                

            }


        }.resume()

    }

}


I have used the model [EmployeResponse].self because we’re getting the response in an array format. If your response are going to be stepping into theDictionary, only then will the output from the network request appear as if this:





Custom key names(Case sensitive and underscore key)-

We can modify our Codable key with custom string keys, but they should match your JSON response keys. 

Swift uses the decodable protocol to internally map the JSON response to a struct or class that inherits from the decodable protocol, you can also use the coding keys enum to instruct swift if it needs to do some custom mapping.
There are scenarios where the API response may have underscore in their keys as- dep_id and emp_id.

{
      "emp_id": 1,
      "Name": "Mr.Sushil Kumar",
      "role": "Developer",
      "org":"AppCodeZip",
      "dep_id":12755
     }

You can update the variable name with an underscore but writing underscore is not good naming convention practice as per the variable declaration we should avoid writing underscore in variables.this is called custom mapping.




struct EmployeResponse : Decodable

{

    let empiddepidInt

    let nameroleorgString


    enum CodingKeysStringCodingKey {

        case depid = "dep_id"

        case empId = "emp_id"

        case name  =  "Name"

        case role,org

    }

}


For your complete source code, you can download the 👉 final project from GitHubAs always, leave us comment and share your thought about the tutorial.

I hope this article was helpful to you. So, please share it together with your friends and colleagues using the social buttons below!

Post a Comment

0 Comments