JSON in Swift — Codable, JSONDecoder & JSONEncoder
Swift's Codable protocol (combining Encodable and Decodable) makes JSON serialisation straightforward and type-safe. The Foundation framework's JSONDecoder and JSONEncoder handle the heavy lifting with minimal boilerplate.
Decode JSON with Codable
Conform your struct or class to Codable and use JSONDecoder to parse a JSON string into a Swift type.
import Foundation
struct User: Codable {
let id: Int
let name: String
let email: String
}
let json = """
{"id":1,"name":"Alice","email":"alice@example.com"}
""".data(using: .utf8)!
let decoder = JSONDecoder()
let user = try decoder.decode(User.self, from: json)
print(user.name) // AliceEncode a struct to JSON
Use JSONEncoder to serialise a Codable value to a Data object, then convert to a String.
let user = User(id: 1, name: "Alice", email: "alice@example.com")
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try encoder.encode(user)
print(String(data: data, encoding: .utf8)!)Customise keys with CodingKeys
Use a CodingKeys enum to map JSON snake_case keys to Swift camelCase property names.
struct User: Codable {
let id: Int
let firstName: String
let lastName: String
enum CodingKeys: String, CodingKey {
case id
case firstName = "first_name"
case lastName = "last_name"
}
}Handle optional fields
Declare optional properties with ? to handle missing or null JSON keys without throwing a decoding error.
struct Profile: Codable {
let id: Int
let bio: String? // may be null or absent
let website: URL? // may be null or absent
}
// Missing "bio" and "website" keys decode fine:
let json = #"{"id": 42}"#.data(using: .utf8)!
let profile = try JSONDecoder().decode(Profile.self, from: json)
print(profile.bio) // nil
print(profile.website) // nilDate decoding strategies
JSONDecoder provides built-in strategies for decoding ISO 8601 dates, Unix timestamps, and custom formats.
struct Event: Codable {
let name: String
let date: Date
}
let decoder = JSONDecoder()
// ISO 8601 string: "2024-06-15T10:30:00Z"
decoder.dateDecodingStrategy = .iso8601
// Unix timestamp (seconds since epoch): 1718443800
decoder.dateDecodingStrategy = .secondsSince1970
// Custom format
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
decoder.dateDecodingStrategy = .formatted(formatter)Decode a JSON array
Decode a top-level JSON array directly into a Swift array of Codable types.
let json = """
[
{"id":1,"name":"Alice","email":"a@example.com"},
{"id":2,"name":"Bob","email":"b@example.com"}
]
""".data(using: .utf8)!
let users = try JSONDecoder().decode([User].self, from: json)
print(users.count) // 2
print(users[0].name) // AliceRelated Tools
Frequently Asked Questions
What is Codable in Swift?▾
Codable is a type alias for Encodable & Decodable. Conforming a struct or class to Codable lets Swift automatically synthesise JSON serialisation and deserialisation code when all stored properties are themselves Codable.
How do I decode JSON in Swift?▾
Create a Codable struct matching the JSON shape, convert the JSON string to Data with .data(using: .utf8), then call JSONDecoder().decode(MyType.self, from: data). The call throws a DecodingError if parsing fails.
How do I map snake_case JSON keys to camelCase Swift properties?▾
Either provide a CodingKeys enum with raw string values (e.g. case firstName = "first_name"), or set decoder.keyDecodingStrategy = .convertFromSnakeCase on your JSONDecoder to apply the conversion automatically.
How do I handle nullable or missing JSON fields in Swift?▾
Declare the property as Optional (String?, Int?, etc.). JSONDecoder treats a null JSON value or a missing key as nil rather than throwing an error.
How do I decode ISO 8601 dates in Swift?▾
Set decoder.dateDecodingStrategy = .iso8601 on your JSONDecoder. For Unix timestamps, use .secondsSince1970 or .millisecondsSince1970. For custom formats, pass a DateFormatter via .formatted(formatter).
JSON in Other Languages
Format and validate your JSON instantly
Free, no ads, no sign-up. Also converts JSON to TypeScript, YAML, CSV, and more.
Open JSON Formatter →If jsondecode.com saved you time, share it with your team
Free forever. No ads. No sign-up. Help other developers find it.