How to create a bridge between JSON from the server and local swift projects

As an iOS developer, you are almost always guaranteed to come across JSON within a project. In this blog post we will discuss how to easily create a bridge between the JSON, coming from the server, and your local swift objects.

What is Codable

Well codable is actually a typealias for the Decodable & Encodable protocols. So the question should rather be, what is Decodable & Encodable ?

Simply put, if your object needs to be converted to JSON, that object must extend Encodable and if you want to convert JSON to a certain object, that object must extend Decodable . If it needs both, then just extend Codable .

Why use Codable

It makes converting JSON objects to swift objects extremely easy without having to write any boilerplate code. Essentially automates the process.

How to use it

Let’s start with a simple example. Consider the following JSON:

{
“name”: “John”,
“surname”: “Doe”

}

(The JSON string, for sake of simplicity, will just be a String object in swift, called jsonString)

Here we have a JSON object representing a Polymorph employee. Now lets create a struct in swift to match this JSON object and extend Codable so that we can decode the JSON object into the struct. We are choosing to make it Codable , because we would also like to encode the object to JSON.

struct PolyPeep: Codable {
var name: String
var surname: String
}

Now for the magic! To decode the JSON into the PolyPeep struct we simply write:

let jsonData = jsonString.data(using: .utf8)!
let polymorphEmployee = try! JSONDecoder ().decode(PolyPeep.self, from: jsonData)

And just like that, you have a polymorphEmployee object that is ready to go.

So how does it work

When you decode the JSON, it uses the struct property names to match it to the JSON property names and then decode it accordingly.

Now you might be thinking, that’s great and all, but what happens if I don’t want to use the same property names that are present in the JSON object?

Don’t worry there’s an easy solution for this situation as well.

Let’s now assume now that we want to convert the following JSON to the exact same Swift object PolyPeep.

{
“name”: “John”,
“surname”: “Doe”

}

Now the keys don’t match anymore (first_name != name). In situations like this, you use CodingKeys. This is used to define the exact key that is associated with each property:

struct  PolyPeep: Codable 
{
var name: String
var surname: String
enumCodingKeys: String, CodingKey {
case name = “first_name”
case surname = “last_name”
}
}

Slightly more complex example

Let’s now have a look at a more complex example to show that the Codable protocol will suit your every JSON need.

enum Role: Int, Codable {
case softwareDeveloper = 0
case softwareTester = 1
case business = 2
case ceo = 3
}
struct PolyPeep: Codable {
var name: String
var surname: String
var employmentDate: Date
var role: Role
}

{
“name” : “John”,
“surname”: “Doe”
“employmentDate”: “2021-06-01T18:32:53+0000”
“role”: “0”
}

Here we show that Codable can handle enums as well as Dates, which are very commonly used. To convert this we only need to specify that date format and the enum’s will handle themselves automatically according to their integer values.

let jsonData = jsonString.data(using: .utf8)!
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let polymorphEmployee = try! decoder.decode(PolyPeep.self, from: jsonData)

It’s also possible to tell the date decoding strategy to use a completely custom type. You can also have nested Codable structs… and the list goes on.

Let’s look at an encode example

Lets use our original PolyPeep struct to demonstrate encoding. First let’s initialize the object:

let polyPeep = PolyPeep(name: “John”, surname: “Doe”)

And then to encode it to a JSON string we simply write:

let jsonData = try! JSONEncoder().encode(user)
print(String(data: jsonData, encoding: .utf8)!
output:
{“name”: “John” , “surname” : “Doe”}

And that’s all there is to it!

Conclusion

And there you have it. I hope this short article was useful and that you will be excited to start using codables.

Resources

1. Here is a helpful tool you can use to generate your swift codable structs: https://app.quicktype.io/ Just hand it the JSON strings and it will pop-out the matching codable structs.
2. Here some more info on encoding & decoding: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
3. Codable Documentation: https://developer.apple.com/documentation/swift/codable

Ryno Claassen
Ryno Claassen
Mobile Developer

Want us to solve your business problem too?

Speak to us about your app development project

"*" indicates required fields

Name*

Enter your details below and our team will get in touch to provide you with more information about our supplementary solutions

I want to know more about:
This field is for validation purposes and should be left unchanged.

Enter your details below to get the free 5 Technology trends currently disrupting the healthcare sector.

Hidden
Enter your details below to get How Predictive Maintenance Can Reduce Manufacturing Breakdowns By Up to 75% for free.
  • Hidden

Request a free consultation

Please complete this form & we will be in touch to set up a meeting.

"*" indicates required fields

Name*