Handling JSON with Codable

Tutorial 3 of 5

Sure, here is the detailed tutorial.

1. Introduction

In this tutorial, we will learn how to handle JSON data in Swift using the Codable protocol. The Codable protocol is a combination of the Encodable and Decodable protocols. It allows us to encode and decode custom data types to and from JSON.

By the end of this tutorial, you will understand:
- How to decode JSON data into Swift objects
- How to encode Swift objects into JSON data

Prerequisites: Basic knowledge of Swift programming.

2. Step-by-Step Guide

Decoding JSON

The process of converting JSON data into Swift objects is known as decoding.

  1. First, we create a struct that matches the JSON structure. This struct should conform to the Codable protocol.
  2. Next, we initiate an instance of JSONDecoder.
  3. Finally, we call the decode(_:from:) method on the JSONDecoder instance.

Encoding JSON

Encoding is the process of converting Swift objects into JSON data.

  1. First, we create a struct that conforms to the Codable protocol.
  2. Next, we initiate an instance of JSONEncoder.
  3. Finally, we call the encode(_:from:) method on the JSONEncoder instance.

3. Code Examples

// Define the struct
struct User: Codable {
    var name: String
    var age: Int
}

// JSON data
let jsonData = """
{
    "name": "John",
    "age": 30
}
""".data(using: .utf8)!

do {
    // Create a decoder
    let decoder = JSONDecoder()

    // Decode the JSON data
    let user = try decoder.decode(User.self, from: jsonData)

    print(user.name) // Prints: John
    print(user.age)  // Prints: 30
} catch {
    print(error)
}

// Create an instance of User
let user = User(name: "Jane", age: 25)

do {
    // Create an encoder
    let encoder = JSONEncoder()

    // Encode the User
    let encodedData = try encoder.encode(user)

    let jsonString = String(data: encodedData, encoding: .utf8)
    print(jsonString) // Prints: Optional("{\"name\":\"Jane\",\"age\":25}")
} catch {
    print(error)
}

4. Summary

We've learned how to handle JSON in Swift using the Codable protocol. We learned how to decode JSON data into Swift objects and encode Swift objects into JSON data.

Next, you might want to learn about handling complex JSON structures, such as nested JSON or JSON arrays.

5. Practice Exercises

Here are some exercises to help you practice:

  1. Create a struct for a JSON that contains an array. Decode it.
  2. Encode a Swift object into JSON, then decode it back into a Swift object.
  3. Handle a case where a key in the JSON does not always exist.

Remember, practice is key to mastering any concept, so keep coding and exploring!