Codable: Encoding and Decoding JSON
Conforming to Codable, custom CodingKeys and nested container decoding.
Codable: Encoding and Decoding JSON is a free Swift Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.
Codable Protocol
Codable is a type alias for Encodable & Decodable. Conforming types can be encoded to and decoded from JSON automatically.
struct User: Codable {
var name: String
var age: Int
}Automatic Synthesis
Swift synthesizes Codable implementations when all stored properties are themselves Codable.
struct Product: Codable {
var id: Int
var title: String
var price: Double
// init(from:) and encode(to:) are auto-generated
}Decoding JSON
Use JSONDecoder to decode Data into your Decodable type.
let json = #"{"name":"Alice","age":30}"#.data(using: .utf8)!
let user = try JSONDecoder().decode(User.self, from: json)
print(user.name) // AliceEncoding to JSON
Use JSONEncoder to encode a Codable value into Data.
let user = User(name: "Bob", age: 25)
let data = try JSONEncoder().encode(user)
print(String(data: data, encoding: .utf8)!)Custom CodingKeys
Use a CodingKeys enum to map between Swift property names and JSON keys.
struct Article: Codable {
var createdAt: Date
enum CodingKeys: String, CodingKey {
case createdAt = "created_at"
}
}Date Decoding Strategies
Configure JSONDecoder.dateDecodingStrategy to parse dates in various formats.
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let article = try decoder.decode(Article.self, from: data)Nested Containers
Decode nested JSON objects by defining nested Codable structs or using keyed containers manually.
struct Response: Codable {
struct Data: Codable {
var users: [User]
}
var data: Data
}
let resp = try JSONDecoder().decode(Response.self, from: json)Custom Decode Logic
Override init(from:) for non-standard JSON structures or to apply transformations during decode.
struct Rating: Codable {
var stars: Int
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let raw = try container.decode(Double.self)
stars = Int(raw.rounded())
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(Double(stars))
}
}keyDecodingStrategy
Use .convertFromSnakeCase to automatically convert JSON snake_case keys to Swift camelCase properties.
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let user = try decoder.decode(User.self, from: data)
// "first_name" → firstNameEncoding Options
Configure JSONEncoder.outputFormatting for pretty-printed or sorted output.
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let data = try encoder.encode(product)Handling Optional Fields
Mark properties as Optional to handle missing JSON keys gracefully without throwing.
struct User: Codable {
var name: String
var bio: String? // nil if "bio" key is absent from JSON
}Quick Check
Which JSONDecoder strategy automatically maps JSON snake_case keys to Swift camelCase property names?
Lesson Recap
Conform to Codable for automatic JSON encode/decode. Use CodingKeys to remap property names, keyDecodingStrategy = .convertFromSnakeCase for APIs with snake_case, custom init(from:) for non-standard JSON, and dateDecodingStrategy for date parsing.
Learn Swift with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 122
- Lessons
- 409
Frequently Asked Questions
Is the “Codable: Encoding and Decoding JSON” lesson free?
Yes — any 3 lessons of the Swift Academy learning path, including “Codable: Encoding and Decoding JSON”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.
What will I learn in “Codable: Encoding and Decoding JSON”?
Conforming to Codable, custom CodingKeys and nested container decoding. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Swift Academy?
No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.
How long does the “Codable: Encoding and Decoding JSON” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Swift Academy lesson?
Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- URLSession data(from:) with async/await
- Codable: Encoding and Decoding JSON
- Error Handling and HTTP Status Codes
- Retry Logic and Background URLSession