JSON and Codable
JSON in One Minute
json
{
"id": 7,
"title": "Swift Basics",
"is_free": true,
"price": 19.99,
"tags": ["swift", "ios"],
"author": { "name": "Asha", "country": "India" }
}
Match it with a Struct
swift
struct Author: Codable {
let name: String
let country: String
}
struct Course: Codable, Identifiable {
let id: Int
let title: String
let isFree: Bool
let price: Double
let tags: [String]
let author: Author
}
Decode
swift
let json = """
{ "id": 7, "title": "Swift Basics", "is_free": true, "price": 19.99,
"tags": ["swift", "ios"], "author": { "name": "Asha", "country": "India" } }
"""
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase // is_free becomes isFree
do {
let course = try decoder.decode(Course.self, from: Data(json.utf8))
print(course.title, course.author.name)
} catch {
print("Decoding failed: \(error)")
}
Names must match: Property names must equal the JSON keys, otherwise decoding fails. Use
convertFromSnakeCase or CodingKeys to map different names.
CodingKeys
swift
struct Movie: Codable {
let id: Int
let title: String
let posterPath: String?
let releaseDate: String
enum CodingKeys: String, CodingKey {
case id, title
case posterPath = "poster_path"
case releaseDate = "release_date"
}
}
Optional and Missing Fields
If a key might be missing or null, make the property optional. Otherwise the whole decode fails.
swift
struct User: Codable {
let name: String
let nickname: String? // can be missing or null
}
Arrays and Wrappers
swift
// Response: { "results": [ {...}, {...} ], "total": 2 }
struct Page<T: Codable>: Codable {
let results: [T]
let total: Int
}
let page = try decoder.decode(Page<Movie>.self, from: data)
Dates
swift
decoder.dateDecodingStrategy = .iso8601 // "2026-11-16T10:00:00Z"
// or: .secondsSince1970, .formatted(formatter)
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
encoder.dateEncodingStrategy = .iso8601
let output = try encoder.encode(course)
print(String(decoding: output, as: UTF8.self))
Custom Decoding
swift
struct Price: Decodable {
let amount: Double
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let number = try? container.decode(Double.self) {
amount = number
} else {
let text = try container.decode(String.self) // API sometimes sends "19.99" as text
amount = Double(text) ?? 0
}
}
}
Debugging Decoding Errors
swift
do {
_ = try decoder.decode(Course.self, from: data)
} catch let DecodingError.keyNotFound(key, context) {
print("Missing key \(key.stringValue): \(context.codingPath)")
} catch let DecodingError.typeMismatch(type, context) {
print("Wrong type \(type): \(context.debugDescription)")
} catch {
print(error)
}
Tip: Paste JSON into a free online JSON-to-Swift generator to create the first version of your structs, then adjust names and optionals.
Conclusion
Codable converts JSON and Swift types with almost no code. Handle snake_case, optional fields and dates with the decoder's strategies.
Quick Summary: Make structs Codable, decode with JSONDecoder, map names with CodingKeys or convertFromSnakeCase, and make unreliable fields optional.

