Codable and JSON
Codable is a magic label that lets Swift automatically translate your custom types into JSON text, and back again.
In this page:
Syntax
import Foundation
struct TypeName: Codable {
var property: Type
}
let data = try JSONEncoder().encode(instance)
let decoded = try JSONDecoder().decode(TypeName.self, from: data)
Encoding a Struct to JSON
A struct conforming to Codable can be turned into JSON Data using JSONEncoder, which is then typically converted to a printable String.
Example: Encoding a Struct to JSON
// Import the `Foundation` module
import Foundation
// Define a struct `User`
struct User: Codable {
var name: String
var age: Int
}
// Declare a constant `user`, set to `User(name: "Nina", age: 29)`
let user = User(name: "Nina", age: 29)
// Declare a constant `data`, set to `try! JSONEncoder().encode(user)`
let data = try! JSONEncoder().encode(user)
// Print `String(data: data, encoding: .utf8)!` to the console
print(String(data: data, encoding: .utf8)!)
Login to try C/C++/Java/PHP code in the editor
Decoding JSON Back into a Struct
JSONDecoder parses JSON Data back into a Codable type, reconstructing the original structured value.
Example: Decoding JSON Back into a Struct
// Import the `Foundation` module
import Foundation
// Define a struct `User`
struct User: Codable {
var name: String
var age: Int
}
// Declare a constant `json`, set to `"{\"name\":\"Leo\",\"age\":34}"`
let json = "{\"name\":\"Leo\",\"age\":34}"
// Declare a constant `data`, set to `json.data(using: .utf8)!`
let data = json.data(using: .utf8)!
// Declare a constant `decoded`, set to `try! JSONDecoder().decode(User.self, from: data)`
let decoded = try! JSONDecoder().decode(User.self, from: data)
// Print "\(decoded.name) is \(decoded.age)" to the console
print("\(decoded.name) is \(decoded.age)")
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting a type must conform to
Codable(orEncodable/Decodable) beforeJSONEncoder/JSONDecodercan process it. - Assuming property names in JSON always match Swift property names exactly; mismatches require a custom
CodingKeysenum. - Forgetting
JSONEncoder().encode(_:)andJSONDecoder().decode(_:from:)are both throwing functions requiringtry.
Chapter Summary
- A type conforming to
Codable(bothEncodableandDecodable) can be automatically converted to and from JSON. JSONEncoder().encode(_:)turns aCodablevalue intoDatacontaining JSON.JSONDecoder().decode(_:from:)parsesDataback into a Swift type.CodingKeyslets you customize how property names map to JSON keys.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: