Skip to content
Learn Netverks

Lesson

Step 33/36 92% through track

codable-json

Codable and JSON

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches Codable and JSON: the syntax, patterns, and safety habits you need before advancing in Swift.

Teams still ship Codable and JSON in Swift codebases—skipping it leaves gaps in debugging and code reviews.

You will apply Codable and JSON in contexts like: REST clients, config files, and persistence layers with Codable.

Write Swift in main.swift with print(), click Run on server—the dev runner swiftc compiles and runs the binary (requires Swift toolchain, typically macOS; LEARNING_RUNNER_ENABLED=true).

Toward the end of the track—consolidate before capstone-style review lessons.

Codable combines Encodable and Decodable for serialization—JSON via JSONEncoder and JSONDecoder, similar to Gson in Java or System.Text.Json in C#.

Encoding and decoding

struct User: Codable {
    let name: String
    let score: Int
}

let user = User(name: "Ada", score: 98)
let data = try JSONEncoder().encode(user)
let decoded = try JSONDecoder().decode(User.self, from: data)

Custom keys and dates

Use CodingKeys enum for snake_case JSON; configure encoder dateEncodingStrategy for ISO-8601.

Important interview questions and answers

  1. Q: Codable vs manual JSON?
    A: Codable is compile-time safe and maintainable; manual dictionaries suit dynamic schema-less payloads.
  2. Q: Optional properties in JSON?
    A: Missing keys decode to nil for optional properties; required properties throw decoding errors.

Self-check

  1. What protocol must types adopt for JSON encoding?
  2. What type converts JSON Data to Swift structs?

Tip: Use CodingKeys when JSON keys use snake_case and Swift properties use camelCase.

Interview prep

Codable benefit?

Compile-time safe serialization vs manual dictionaries.

Missing JSON keys?

Optional properties decode to nil; required properties throw.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • Codable synthesis?
  • JSONDecoder keys?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump