Swift Tutorials: JSONEncoder and JSONDecoder

beginner
23 min

Swift Tutorials: JSONEncoder and JSONDecoder

Welcome to our deep dive into Swift's JSONEncoder and JSONDecoder! In this comprehensive guide, we'll explore how to convert Swift data into JSON and vice versa. Let's get started!

Understanding JSON

JSON (JavaScript Object Notation) is a lightweight data interchange format that's easy for humans to read and write and easy for machines to parse and generate. It's widely used to transmit data between a server and a client, like a web application and a mobile app.

What are JSONEncoder and JSONDecoder?

JSONEncoder and JSONDecoder are Swift's built-in classes that help you convert your Swift data into JSON and back. They're essential tools for working with APIs and networking in Swift.

šŸ’” Pro Tip: If you're working with Codable types (which we'll discuss later), you can use JSONEncoder and JSONDecoder with just a few lines of code!

Codable Types

Codable is a protocol in Swift that conforms to encoding and decoding using JSONEncoder and JSONDecoder. Any type that conforms to Codable can be easily encoded and decoded as JSON.

Encodable Types

A type that conforms to the Encodable protocol can be converted into JSON.

swift
struct Person: Encodable { let name: String let age: Int }

In this example, Person is an Encodable type with properties name and age.

Decodable Types

A type that conforms to the Decodable protocol can be converted from JSON into a Swift object.

swift
struct Person: Decodable { let name: String let age: Int }

In this example, Person is a Decodable type with properties name and age.

šŸ“ Note: A type that conforms to Codable automatically conforms to both Encodable and Decodable.

Encoding JSON with JSONEncoder

Now that you understand Codable types, let's see how to use JSONEncoder to encode JSON.

swift
let person = Person(name: "John Doe", age: 30) let jsonData = try! JSONEncoder().encode(person) let jsonString = String(data: jsonData, encoding: .utf8) print(jsonString ?? "")

In this example, we create a Person object, encode it using JSONEncoder, and convert the resulting data to a JSON string.

Decoding JSON with JSONDecoder

To decode JSON using JSONDecoder, follow these steps:

swift
let jsonData = Data("{\"name\":\"Jane Doe\",\"age\":35}".utf8)! let person = try! JSONDecoder().decode(Person.self, from: jsonData) print(person)

In this example, we create a JSON string and decode it into a Person object using JSONDecoder.

Advanced Example

Let's dive into an advanced example where we create an API request using URLSession, encode and decode JSON, and handle potential errors.

swift
struct APIResponse: Decodable { let people: [Person] } struct Person: Decodable { let name: String let age: Int } func fetchPeople() { let url = URL(string: "https://api.example.com/people")! let task = URLSession.shared.dataTask(with: url) { data, response, error in if let error = error { print("Error: \(error)") return } guard let data = data else { print("No data received") return } do { let people = try JSONDecoder().decode(APIResponse.self, from: data) print("Fetched \(people.people.count) people:") for person in people.people { print("\(person.name) - \(person.age)") } } catch { print("Decoding error: \(error)") } } task.resume() }

In this example, we create an API request, decode the JSON response into an array of Person objects, and handle potential errors.

Quick Quiz
Question 1 of 1

What is JSON?

Quick Quiz
Question 1 of 1

What does Codable do in Swift?

Quick Quiz
Question 1 of 1

How do you encode JSON using JSONEncoder in Swift?

Quick Quiz
Question 1 of 1

How do you decode JSON using JSONDecoder in Swift?