Parse JSON in Swift
Decode JSON into strongly typed Swift structs with JSONDecoder and the Codable protocol.
Also known as: Decode JSON in Swift, Codable JSON Swift
beginner
Swift's Codable lets JSONDecoder map JSON directly onto your model types. Declare a struct that conforms to Codable and decode the raw Data.
What it is
Swift decodes JSON by mapping it onto a type that conforms to Codable (an alias for Encodable & Decodable). You describe the shape once as a struct, and JSONDecoder does the parsing, throwing a typed error if the data does not match.
When JSON keys use snake_case but you want Swift's camelCase properties, set decoder.keyDecodingStrategy = .convertFromSnakeCase instead of writing manual CodingKeys. Decoding is throwing, so wrap it in do/catch (or try?) rather than force-unwrapping.
Worked example
import Foundation
struct User: Codable {
let id: Int
let fullName: String
}
let json = """
{ "id": 7, "full_name": "Ada Lovelace" }
""".data(using: .utf8)!
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
let user = try decoder.decode(User.self, from: json)
print(user.fullName) // Ada Lovelace
} catch {
print("Decoding failed: \(error)")
}
Failure mode — when it misleads
A single type mismatch or missing non-optional key throws and aborts the whole decode. Mark genuinely optional fields as Optional (e.g. let nickname: String?) so absent keys don't fail the entire object, and always handle the thrown error instead of using try!.
Related entries
Sources & further reading
- Encoding and Decoding Custom Types (article)