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!
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.
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 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.
A type that conforms to the Encodable protocol can be converted into JSON.
struct Person: Encodable {
let name: String
let age: Int
}In this example, Person is an Encodable type with properties name and age.
A type that conforms to the Decodable protocol can be converted from JSON into a Swift object.
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.
Now that you understand Codable types, let's see how to use JSONEncoder to encode JSON.
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.
To decode JSON using JSONDecoder, follow these steps:
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.
Let's dive into an advanced example where we create an API request using URLSession, encode and decode JSON, and handle potential errors.
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.
What is JSON?
What does Codable do in Swift?
How do you encode JSON using JSONEncoder in Swift?
How do you decode JSON using JSONDecoder in Swift?