JSONDecoder: Turning JSON into Swift Types

JSONDecoder is your translator for turning raw JSON data into native Swift structs or classes. It's the standard way to parse API responses, letting you work with typed, safe objects.
WHY IT EXISTS: Modern apps are constantly fetching data from web APIs, which almost always speak JSON. Your Swift code, however, works best with strongly-typed, structured data like a User struct. JSONDecoder exists to bridge this gap, automating the tedious and error-prone process of converting unstructured JSON text into safe, usable Swift objects.
THE MENTAL MODEL: Think of JSONDecoder as an automated factory machine. You give it a blueprint (your Codable Swift struct) and a pile of raw materials (the JSON Data from a server). The machine reads the blueprint, assembles the materials accordingly, and outputs a finished, structured Swift object you can use immediately in your code.
HOW IT WORKS: First, you define a Swift struct or class that conforms to the Codable protocol. Its properties must mirror the structure of the JSON you expect. Second, you get your JSON as a Data object, typically from a network request. Finally, you create an instance of JSONDecoder and call its decode(_:from:) method, passing your Swift type and the Data. If the JSON matches your type, it returns an initialized instance; otherwise, it throws an error.
WHEN TO USE IT: Use JSONDecoder whenever you need to parse JSON in a Swift application. This is the default, idiomatic way to handle network API responses. It's also perfect for reading configuration files or any other data stored in JSON format. Its type-safety makes it far superior to older, manual parsing methods.
WHEN NOT TO USE IT: For non-JSON data formats like XML, CSV, or Protocol Buffers, you will need to use a different, format-specific parsing library. While you could use the older JSONSerialization for one-off value extraction, it's less safe and generally not recommended over defining a proper Codable type.
ONE CANONICAL EXAMPLE: Many APIs use "snake_case" for keys, like {"user_id": 123, "display_name": "Alex"}. A naive Swift struct struct User: Codable { let userId: Int; let displayName: String } would fail to decode this. The best fix is to configure the decoder before calling decode: set decoder.keyDecodingStrategy = .convertFromSnakeCase. This tells the decoder to automatically map keys like user_id to properties like userId, keeping your Swift code clean.
Read the original → developer.apple.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.