JSON basics, encoding and decoding with Swift
Tags: swift, json, beginners, ios
Published: 2023-10-11 09:47:11

This is a first part of a beginner series, where we understand basic of networking in Swift.

To simplify it greatly, **[JSON](https://en.wikipedia.org/wiki/JSON)(Javascript Object Notation)** is the way most clients and servers, share data with each other.

Here is a sample json, that fetches list of followers for a users profile:

```json
{
  "userId": "123456",
  "userName": "John Doe",
  "followers": [
    {
      "followerId": "789012",
      "followerUsername": "follower1_username",
      "followerName": "Follower One"
    },
    {
      "followerId": "345678",
      "followerUsername": "follower2_username",
      "followerName": "Follower Two"
    },
    {
      "followerId": "901234",
      "followerUsername": "follower3_username",
      "followerName": "Follower Three"
    }
  ]
}

```

---

### JSON Decoding

One of the most basic things you will do as part of networking in Swift, is displaying the data received from server into some UI. Lets take the above JSON as an example. To do this we have to decode the JSON response into a object in Swift that we can reason about. 

Firstly we will create a `struct` in Swift that can be mapped to the json response.

```swift
//1
struct User: Decodable {
    //2
    let userId: String
    let userName: String
    let followers: [Follower]
    
    struct Follower: Decodable {
        let followerId: String
        let followerUsername: String
        let followerName: String
    }
}
```
_**Note**: Here we are using exact same keys as in the json response. More about custom keys in a later article._

1. The struct we created is confirming to `Decodable` protocol, which is required for the json to be decoded to a Swift object.
2. If you notice, all the properties we used here have the same key with the json. This is important as the mapping happens between same keys(case-sensitive). Of-course we can customise the keys based on our needs, this will be covered in a later article.

Now lets write the code to decode this json.

```swift 
//1
let json = """
{
  "userId": "123456",
  "userName": "John Doe",
  "followers": [
    {
      "followerId": "789012",
      "followerUsername": "follower1_username",
      "followerName": "Follower One"
    },
    {
      "followerId": "345678",
      "followerUsername": "follower2_username",
      "followerName": "Follower Two"
    },
    {
      "followerId": "901234",
      "followerUsername": "follower3_username",
      "followerName": "Follower Three"
    }
  ]
}
"""

//2
if let data = json.data(using: .utf8) {
    
    //3
    if let userObj = try? JSONDecoder().decode(User.self, from: data) {
        print(userObj)
    } else {
        print("Decoding failed")
    }
} else {
    print("Error getting json data")
}

```

1. We will use Swift's multiline string literals to store json into a property.
2. This line converts the json string into a `Data` object where the characters of the string are encoded using UTF-8.
3. This line uses the instance method of `JSONDecoder` to specify the type of the object(ie. `User`) that we want and passing the `data` for decoding.


![Xcode console response for User object](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lenf3v06wcplzbbcsny0.png)

Now we can see the `User` object being printed in Xcode console.

This can help you get started with displaying data received from your server.

---

### JSON Encoding

Most of the times, we also have to send some or the other data back to the server. For example, 

- User searches something in your app
- User authentication
- Save user data to server

In the above cases, you will have to send some form of data as part of your `httpBody`. In these kind of scenarios we have to convert our Swift object to an encoded data. Lets look into how we can do that.

First things first, we have to update our User struct to be encodable. For this we have to conform to the `Encodable` protocol. But as we already have a conformance to `Decodable`, there is an easier way to do this: `Codable`

`Codable` is literally conbination of `Encodable` and `Decodable` protocols. 

```swift
typealias Codable = Decodable & Encodable
```

Updated `User struct`

```swift
struct User: Codable {
    let userId: String
    let userName: String
    let followers: [Follower]
    
    struct Follower: Codable {
        let followerId: String
        let followerUsername: String
        let followerName: String
    }
}
```

---

Now lets see how to encode the User object.

```swift
func encode(user: User) {
    //1
    if let encodedData = try? JSONEncoder().encode(user) {
        //2
        if let jsonString = String(data: encodedData, encoding: .utf8) {
            print(jsonString)
        }
    }
}
```

1. We pass the `User` object to be encoded to `JSONEncoder`'s `encode` function. If encoding is successful we will get encoded `Data`, which we use based on our needs (ie. Send to server via the api, or print the encoded String as we do here)
2. We pass the encoded data to `String`'s initializer and print the json string which is returned. This json string is exactly same as the json that we created in the beginning.

Console response below 👇
![Xcode console response for encoded json string](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6j049kwo4hmbol1564ho.png)

Thats a wrap on basics of encoding and decoding json in Swift!

All the code available in Github [gist](https://gist.github.com/jyothishjohnson/652c31fc627059de0efdaf003460174d)

---


🗨️💡 _Join the Conversation! Share Your Thoughts Below._

🗣️ _Your opinion matters! Eager to hear your take on this topic. Don't hold back—let's dive into a lively discussion!_

_Enjoyed this Article?_

💖 _React: Click the heart icon to show your appreciation and help others discover this content too!_

🔔 _Follow for more Swift/iOS content!_ [@jyo_johnson on X(Twitter)](https://twitter.com/jyo_johnson)

🚀 _Share: Spread the knowledge! Share this article with your network._

_Your engagement is what keeps our community thriving. Thank you for being a part of it!_