The Codable protocol helps your app easily convert data between Swift objects and JSON format. This makes reading and saving data simple and safe.
0
0
Codable protocol for JSON parsing in iOS Swift
Introduction
When you want to load data from a web service that sends JSON.
When you need to save app data as JSON files on the device.
When you want to send data from your app to a server in JSON format.
When you want to convert JSON data into Swift objects to use in your app.
When you want to convert Swift objects into JSON to share or store.
Syntax
iOS Swift
struct MyData: Codable {
var name: String
var age: Int
}Use Codable on structs or classes to make them able to convert to/from JSON.
Properties must be standard types like String, Int, Double, Bool, or other Codable types.
Examples
A simple user struct that can be encoded to or decoded from JSON.
iOS Swift
struct User: Codable {
var username: String
var score: Int
}This struct can represent a product and be converted to JSON easily.
iOS Swift
struct Product: Codable {
var id: Int
var name: String
var price: Double
}Optional properties like
message can be nil if JSON does not include them.iOS Swift
struct Response: Codable {
var success: Bool
var message: String?
}Sample App
This example shows how to decode a JSON string into a Person object using Codable. It prints the person's name and age.
iOS Swift
import Foundation struct Person: Codable { var name: String var age: Int } let jsonString = "{\"name\": \"Alice\", \"age\": 30}" if let jsonData = jsonString.data(using: .utf8) { let decoder = JSONDecoder() if let person = try? decoder.decode(Person.self, from: jsonData) { print("Name: \(person.name), Age: \(person.age)") } else { print("Failed to decode JSON") } }
OutputSuccess
Important Notes
Always handle decoding errors safely using try? or do-catch.
Use JSONEncoder to convert Swift objects back to JSON data.
Codable works best with simple data types and nested Codable structs.
Summary
Codable makes converting between Swift objects and JSON easy.
Use JSONDecoder to read JSON into Swift objects.
Use JSONEncoder to write Swift objects as JSON.