How to Parse JSON in Swift: Simple Guide with Examples
To parse JSON in Swift, use the
Codable protocol to define your data model and JSONDecoder to convert JSON data into Swift objects. This approach is safe, clean, and recommended for modern Swift apps.Syntax
Parsing JSON in Swift involves three main parts: defining a struct that conforms to Codable, creating a JSONDecoder instance, and calling decode(_:from:) to convert JSON data into your Swift model.
- Codable: A protocol that combines
EncodableandDecodablefor easy JSON encoding and decoding. - JSONDecoder: A class that decodes JSON data into Swift types.
- decode(_:from:): Method to decode JSON data into the specified type.
swift
struct User: Codable {
let id: Int
let name: String
let email: String
}
let jsonData: Data = ... // your JSON data
let decoder = JSONDecoder()
let user = try decoder.decode(User.self, from: jsonData)Example
This example shows how to parse a JSON string representing a user into a Swift User struct using JSONDecoder. It prints the user's name after decoding.
swift
import Foundation struct User: Codable { let id: Int let name: String let email: String } let jsonString = "{\"id\": 1, \"name\": \"Alice\", \"email\": \"alice@example.com\"}" if let jsonData = jsonString.data(using: .utf8) { let decoder = JSONDecoder() do { let user = try decoder.decode(User.self, from: jsonData) print("User name: \(user.name)") } catch { print("Failed to decode JSON: \(error)") } }
Output
User name: Alice
Common Pitfalls
Common mistakes when parsing JSON in Swift include:
- Not matching the JSON keys with your struct property names exactly.
- Forgetting to mark your struct as
Codable. - Not handling decoding errors with
do-catch. - Trying to decode JSON data that is not valid or incomplete.
Use CodingKeys enum inside your struct to map JSON keys to different property names if needed.
swift
struct User: Codable {
let id: Int
let fullName: String
enum CodingKeys: String, CodingKey {
case id
case fullName = "name"
}
}Quick Reference
- Codable: Protocol for JSON encoding/decoding.
- JSONDecoder: Use to decode JSON data.
- decode(_:from:): Method to convert JSON to Swift object.
- CodingKeys: Map JSON keys to different property names.
- do-catch: Handle decoding errors safely.
Key Takeaways
Use Codable structs and JSONDecoder to parse JSON safely and cleanly in Swift.
Match your struct property names to JSON keys or use CodingKeys to map them.
Always handle decoding errors with do-catch to avoid crashes.
Convert JSON strings to Data using utf8 encoding before decoding.
Test your JSON parsing with sample data to catch issues early.