Decoding with JSONDecoder
Parse JSON data into typed Swift values.
Decoding with JSONDecoder is a free Swift Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Creating a JSONDecoder
JSONDecoder rebuilds a Swift value from JSON Data. You tell it the type to produce and hand it the bytes.
import Foundation
struct City: Codable {
var name: String
var population: Int
}
let json = "{\"name\":\"Oslo\",\"population\":700000}"
let data = json.data(using: .utf8)!
let city = try JSONDecoder().decode(City.self, from: data)
print(city.name, city.population)Passing the Type with .self
The first argument is the metatype — written MyType.self. This tells the decoder which structure to build from the data.
import Foundation
struct Flag: Codable { var ok: Bool }
let data = "{\"ok\":true}".data(using: .utf8)!
let result = try JSONDecoder().decode(Flag.self, from: data)
print(result.ok)Decoding Arrays
To decode a JSON array, ask for an array type such as [Int].self or [MyStruct].self.
import Foundation
let json = "[10, 20, 30]"
let data = json.data(using: .utf8)!
let numbers = try JSONDecoder().decode([Int].self, from: data)
print(numbers.reduce(0, +))Decoding Nested Objects
Nested JSON objects map to nested Codable structs. The decoder walks the tree and fills each level for you.
import Foundation
struct Coord: Codable { var lat: Double; var lon: Double }
struct Place: Codable { var name: String; var coord: Coord }
let json = "{\"name\":\"X\",\"coord\":{\"lat\":1.0,\"lon\":2.0}}"
let p = try JSONDecoder().decode(Place.self, from: json.data(using: .utf8)!)
print(p.coord.lat, p.coord.lon)Catching Decode Errors
decode throws when the data does not match the type. Wrap it in do/catch to handle malformed input gracefully.
import Foundation
struct User: Codable { var name: String }
let bad = "{\"wrong\":1}".data(using: .utf8)!
do {
let u = try JSONDecoder().decode(User.self, from: bad)
print(u.name)
} catch {
print("Failed:", error)
}keyNotFound Errors
A common failure is DecodingError.keyNotFound, thrown when a required key is missing. Pattern-match the error to report exactly what went wrong.
import Foundation
struct User: Codable { var name: String }
let bad = "{}".data(using: .utf8)!
do {
_ = try JSONDecoder().decode(User.self, from: bad)
} catch let DecodingError.keyNotFound(key, _) {
print("Missing key:", key.stringValue)
} catch {
print("Other error:", error)
}typeMismatch Errors
If a value has the wrong JSON type — say a string where an Int is expected — the decoder throws DecodingError.typeMismatch.
import Foundation
struct Count: Codable { var n: Int }
let bad = "{\"n\":\"oops\"}".data(using: .utf8)!
do {
_ = try JSONDecoder().decode(Count.self, from: bad)
} catch let DecodingError.typeMismatch(type, _) {
print("Type mismatch, expected:", type)
} catch {
print("Other:", error)
}dataCorrupted Errors
Invalid JSON syntax raises DecodingError.dataCorrupted. This usually means the bytes are not valid JSON at all.
import Foundation
struct User: Codable { var name: String }
let bad = "not json".data(using: .utf8)!
do {
_ = try JSONDecoder().decode(User.self, from: bad)
} catch is DecodingError {
print("Decoding failed: data corrupted")
} catch {
print("Other:", error)
}Decoding into Optionals
If a property is optional, a missing key decodes to nil without throwing. This makes optional fields tolerant of absent data.
import Foundation
struct Profile: Codable {
var name: String
var bio: String?
}
let json = "{\"name\":\"Kai\"}"
let p = try JSONDecoder().decode(Profile.self, from: json.data(using: .utf8)!)
print(p.name, p.bio ?? "no bio")Reusing a Decoder
Like the encoder, a configured JSONDecoder can be reused for many payloads. Keep one instance and decode different inputs with it.
import Foundation
struct Word: Codable { var text: String }
let decoder = JSONDecoder()
let inputs = ["{\"text\":\"hi\"}", "{\"text\":\"bye\"}"]
for s in inputs {
let w = try decoder.decode(Word.self, from: s.data(using: .utf8)!)
print(w.text)
}Decode, Inspect, Use
A full flow: receive Data, decode to a typed value inside do/catch, and then use the strongly typed result safely.
import Foundation
struct Weather: Codable {
var city: String
var temp: Double
}
let json = "{\"city\":\"Rome\",\"temp\":21.5}"
do {
let w = try JSONDecoder().decode(Weather.self, from: json.data(using: .utf8)!)
print("\(w.city): \(w.temp)C")
} catch {
print("Decode error:", error)
}Quick Check: JSONDecoder
Test your decoding knowledge.
Recap: Decoding with JSONDecoder
You learned to rebuild Swift values from JSON:
decode(MyType.self, from: data)produces a typed value.- Arrays, nested objects, and optionals decode automatically.
decodethrowsDecodingErrorcases:keyNotFound,typeMismatch,dataCorrupted,valueNotFound.- Wrap calls in
do/catchto handle malformed input.
Frequently asked questions
Is the “Decoding with JSONDecoder” lesson free?
Yes — the full text of “Decoding with JSONDecoder” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.
What will I learn in “Decoding with JSONDecoder”?
Parse JSON data into typed Swift values. 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; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Decoding with JSONDecoder” 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
- Conforming to Codable
- Encoding with JSONEncoder
- Decoding with JSONDecoder
- Handling Optional and Nested Types