Codable and JSON Serialization

Introduction

Welcome, everyone. Today, you will learn how to convert an object to a json file vice versa with a single line of code. If you have never worked with JSON before, don’t you worry. I will walk you through.

Problem

Map JSON to Object in one line of code and the opposite

Introducing JSON

How to resemble a json file as seen in the previous lesson.

  1. let republicOfKorea = JSON(dictionary: [
  2. "capital": "Seoul",
  3. "name": "Republic of Korea",
  4. "population": 50000000
  5. ])

The json format above would look,

  1. {
  2. "capital": "Seoul",
  3. "name:": "Repulibc of Korea",
  4. "population": 50000000
  5. }

When you make an API call, https://itunes.apple.com/lookup?id=909253you will receive data from the server,

  1. {
  2. "resultCount":1,
  3. "results": [
  4. {"wrapperType":"artist", "artistType":"Artist", "artistName":"Jack Johnson", "artistLinkUrl":"https://itunes.apple.com/us/artist/jack-johnson/id909253?uo=4", "artistId":909253, "amgArtistId":468749, "primaryGenreName":"Rock", "primaryGenreId":21}]
  5. }

Let us attempt to convert an object to a json format using the encode API introduced in Swift 4.

Import Foundation

First thing first, import Foundation.

  1. import Foundation

Design Model

Let us create a blueprint for an object.

  1. struct User: Codable {
  2. var name : String
  3. var loginMethods : [LoginMethods]
  4. var numberOfFriends : Int
  5. }
  6. enum LoginMethods: String, Codable {
  7. case facebook, instagram, linkedin, twitter
  8. }

Create Object

  1. let bob = User(name: "Up", loginMethods: [.facebook, .instagram], numberOfFriends : 4)

That’s right. I have 4 friends.

Encode (Object to JSON)

Let’s attempt convert the bobobject to a json format

  1. //: Create Encoder
  2. let jsonEncoder = JSONEncoder()

Customize Encoder

You may customize how the final form of json would look like as shown below. You don’t have to.

  1. jsonEncoder.outputFormatting = .prettyPrinted
  2. jsonEncoder.dataEncodingStrategy = .base64Encode

Execution

Let us convert the bob object to json using the jsonEncoder object.

  1. //: Encode
  2. var data: Data?
  3. do {
  4. let jsonData = try jsonEncoder.encode(bob)
  5. data = jsonData
  6. let jsonString = String(data: jsonData, encoding: .utf8)
  7. print("JSON String : " + jsonString!)
  8. }
  9. catch(let error) {
  10. print(error)
  11. }

You could technically execute the above method in one line of code using try!. But, it’s better to handle error so that no one goes wild.

  1. JSON String : {
  2. "name" : "Up",
  3. "loginMethods" : [
  4. "facebook",
  5. "instagram"
  6. ],
  7. "numberOfFriends" : 4
  8. }

Decode (JSON to Object)

Let’s attempt to convert the json file to an object using JSONDecoder.

Create Decoder

  1. let jsonDecoder = JSONDecoder()

Execution

  1. do {
  2. let bob = try jsonDecoder.decode(User.self, from: data!)
  3. // let bob = try jsonDecoder.decode(AnotherUser.self, from: data!)
  4. print("Name : \(bob.name)")
  5. print("Number of friends: \(bob.numberOfFriends)")
  6. } catch(let error) {
  7. print(error)
  8. }

The bob local constant has been created within the do block based on the type of User. The json format has to match with the data model structure of the class/struct parameter. If not, you will get an error.

Final Thought

JSONEncoder and JSONDecoder are powerful features. However, you still have to be cautious since the data structure of the object must match with that of the json file. If not, it’s not great. Make sure you are aware.

Source Code

9004_json_serialization_codable

Resources

Itunes JSON API

Working with JSON in Swift - Apple

How to parse Json in Swift - Roadfile Software

Swift JSON Tutorial - Ray Wenderlich

Conclusion

In this lesson, we haven’t learned how to parse and map a json file using the old approach since you can find those things anywhere on the internet. In fact, I have attached a couple resources for you to take a look at if you want.

However, you’ve learned how to convert an object to a json file by conforming to the Codable protocol. And, you’ve learned how to map a json file to an object with one line of code. Still, you have to cautious since the blueprint/data structure must match together.