JSON Parsing in Swift by using codable

Yuvraj Kale
3 min readMay 3, 2020

--

Many developers interact with API response and parsing of the data to the Custom type or your Custom type to JSON. For that everyone chooses different ways like for loop and etc which is the right but not optimized way. Here I am going to explain the codable concept here.

Encoding

Encoding means converting your custom type to JSON type which is accepted by API.

Decoding

Decoding means converting your response data to costume type.

For both of these, we need to confirm an encodable and decodable protocol by custom type.

Codable

Is the other protocol which is combined with encodable & decodable. Means by confirming single codable protocol we can do encoding and decoding. For better understanding, we are using an example where we are getting the detail of students from API.

Following is the response we are getting

{
name:”Yuvraj”,
age:28,
birthdate:”11/05/1991”,
subject:[
{name:"ABC",id:1},
{name:"XYZ",id:2}
]
}

In the above example, you can see that student data having a name as String, age as Int, birthdate as String, subject as an array of a subject with again contains name as String and id as Int.

In the old way, you were like to parse it and store it in Dictionary and use the dictionary in all the app or we were creating a simple structure then assigning each and every value of dictionary to it in for loop which is actually lengthy process.

Here codable plays an important role to optimize this lengthy process which we can see in following example

struct student:codable{
var name:String = ""
var age:Int = 0
var birthdate:String = ""
var subject=[mysubjects]()
}
struct mysubjects{
var name:String = ""
var id:Int = 0
}

In the above example, you can see that student is codable which is actually we use to parse in custom type from JSON and another similar thing is keys are same in response and student structure. we created another structure called mysubjects which is used for the subject. Now how this is parsed let’s see in the following line.

consider data is response from our API.

let student = try JSONDecoder().decode(student.self, from: data)

This is single line parsing which and you can use that student object to get the value like following

print("name = \(student.name)")
print("subject = \(student.subject[0].name)")

Which print the following detail

name = "Yuvraj"
subject = "ABC"

Now the question is what if I am getting an array of students and how can I parse it. For example, I am getting the following response

[
{
name:"Yuvraj",
age:28,
birthdate:"11/05/1991",
subject:[
{name:"ABC",id:1},
{name:"XYZ",id:2}
]
},
{
name:"Rohan",
age:28,
birthdate:”11/01/1992”,
subject:[
{name:"ABC",id:1},
{name:"XYZ",id:2}
]
}
]

In the first example, we have only one response of in key-value pair then we converted it but what if we have an array and how can I convert it? Don’t worry this is very simple to convert. Check the following code.

let student = try JSONDecoder().decode([student].self, from: data)

If you check it carefully you can see the only difference and that student is added in square bracket i.e [].

Conclusion
Codable is a powerful feature in swift which is used to parse JSON data by using a single line. Codable provides us better error handling than many third party library which we used for JSON serialization/deserialization.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Yuvraj Kale
Yuvraj Kale

No responses yet

Write a response