← Back to Swift Course | Chapter 14: Standard Library & Best Practices | Lesson 3 of 7

Codable and JSON

Codable is a magic label that lets Swift automatically translate your custom types into JSON text, and back again.

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

markup
import Foundation
struct User: Codable {
    var name: String
    var age: Int
}
let user = User(name: "Nina", age: 29)
let data = try! JSONEncoder().encode(user)
print(String(data: data, encoding: .utf8)!)

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

markup
import Foundation
struct User: Codable {
    var name: String
    var age: Int
}
let json = "{\"name\":\"Leo\",\"age\":34}"
let data = json.data(using: .utf8)!
let decoded = try! JSONDecoder().decode(User.self, from: data)
print("\(decoded.name) is \(decoded.age)")
Common Mistakes
  1. Forgetting a type must conform to Codable (or Encodable/Decodable) before JSONEncoder/JSONDecoder can process it.
  2. Assuming property names in JSON always match Swift property names exactly; mismatches require a custom CodingKeys enum.
  3. Forgetting JSONEncoder().encode(_:) and JSONDecoder().decode(_:from:) are both throwing functions requiring try.
Chapter Summary
  • A type conforming to Codable (both Encodable and Decodable) can be automatically converted to and from JSON.
  • JSONEncoder().encode(_:) turns a Codable value into Data containing JSON.
  • JSONDecoder().decode(_:from:) parses Data back into a Swift type.
  • CodingKeys lets 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.