JSON Parsing with Codable (Swift) 🎯

beginner
9 min

JSON Parsing with Codable (Swift) 🎯

Welcome to this comprehensive guide on JSON Parsing using Codable in Swift! This tutorial is designed for both beginners and intermediate learners, so let's dive in without any fuss. 🐠

What is JSON Parsing? 📝

JSON (JavaScript Object Notation) is a popular data format with a diverse range of applications. JSON Parsing is the process of converting a JSON string into native Swift data types and vice versa.

Why JSON Parsing? 💡

JSON is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. JSON Parsing is essential when you're dealing with data from APIs, databases, or files.

What is Swift's Codable Protocol? 📝

Swift's Codable protocol is a way of defining types that can be encoded to JSON and decoded from JSON. It's a combination of the Encodable and Decodable protocols.

Setting Up a Simple JSON Model 💡

Let's start by creating a simple JSON model.

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

In the above code, we've defined a Person struct that conforms to the Codable protocol. It has two properties, name and age, which will be encoded as JSON strings and integers respectively.

Encoding with JSONEncoder 💡

To encode our Person object into a JSON string, we'll use JSONEncoder.

swift
let person = Person(name: "John Doe", age: 30) let encoder = JSONEncoder() encoder.encode(person) { (encoder) in // Configure the encoder here if needed } .responseData { (response: DataResponse<Data>) in switch response.result { case .success(let data): print("Encoded JSON: \(data)") case .failure(let error): print("Error encoding JSON: \(error)") } }

In the above code, we first create a Person instance, then create a JSONEncoder and configure it if needed. Finally, we encode the Person instance and handle the result, printing the encoded JSON.

Decoding with JSONDecoder 💡

To decode a JSON string into a Person object, we'll use JSONDecoder.

swift
let jsonString = """ { "name": "Jane Doe", "age": 25 } """ let decoder = JSONDecoder() decoder.decode(Person.self, from: Data(jsonString.utf8)) { (decoder) in // Handle decoding errors here if needed } .response { (result: Result<Person, Error>) in switch result { case .success(let person): print("Decoded Person: \(person)") case .failure(let error): print("Error decoding JSON: \(error)") } }

In the above code, we first create a JSON string representing a Person. Then, we create a JSONDecoder and decode the JSON string into a Person object. Finally, we handle the result, printing the decoded Person.

Real-world Application 💡

Let's see how we can use JSON Parsing with Codable in a real-world application. Suppose we have a User class that conforms to Codable, and we want to fetch user data from an API.

swift
struct User: Codable { let id: Int let name: String let email: String } func fetchUserData(completion: @escaping (User?, Error?) -> Void) { let url = URL(string: "https://api.example.com/users/1")! let task = URLSession.shared.dataTask(with: url) { (data, response, error) in if let error = error { completion(nil, error) return } guard let data = data else { completion(nil, NSError(domain: "Data error", code: -1, userInfo: nil)) return } do { let user = try JSONDecoder().decode(User.self, from: data) completion(user, nil) } catch { completion(nil, error) } } task.resume() } fetchUserData { (user, error) in if let user = user { print("Fetched user: \(user)") } else if let error = error { print("Error fetching user: \(error.localizedDescription)") } }

In the above code, we've defined a User struct that conforms to Codable. We also have a fetchUserData function that fetches user data from an API using URLSession, decodes it into a User object using JSONDecoder, and calls the completion handler with the result.

Quiz 📝

Quick Quiz
Question 1 of 1

What is JSON Parsing in Swift?