0Pricing
Swift Academy · Lesson

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 — lesson 2 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.

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) // Alice

Encoding 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" → firstName

Encoding 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.

Frequently asked questions

Is the “Codable: Encoding and Decoding JSON” lesson free?

Yes — the full text of “Codable: Encoding and Decoding JSON” 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 “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; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

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

  1. URLSession data(from:) with async/await
  2. Codable: Encoding and Decoding JSON
  3. Error Handling and HTTP Status Codes
  4. Retry Logic and Background URLSession
← Back to Swift Academy