JSONEncoder: Turning Swift Objects into JSON

JSONEncoder is your app's translator, converting Swift objects into JSON data for APIs. It's the "serialization" half of Codable. Use it to send data to a server or save objects. The footgun: mismatched keys or date formats require configuring the encoder.
WHY IT EXISTS JSONEncoder was created to provide a standard, type-safe way to convert Swift data structures into JSON. Before the Codable system, developers often manually built JSON strings or used third-party libraries, a process that was verbose and highly error-prone. JSONEncoder streamlines serialization into a few declarative lines of code.
THE MENTAL MODEL Think of JSONEncoder as a specialized packing service for your app's data. You give it a Swift object (like a struct or class), and it neatly packages it into a universally understood format (JSON), ready to be shipped over the network to a server or stored in a file. It handles all the details of converting Swift types like String, Int, and Date into their JSON equivalents.
HOW IT WORKS First, you ensure your Swift type conforms to the Encodable protocol. This signals to the compiler that your object can be encoded. Then, you create an instance of JSONEncoder. You can customize its behavior through properties. For example, outputFormatting = .prettyPrinted makes the JSON human-readable, and dateEncodingStrategy defines how Date objects are represented (e.g., as a timestamp or an ISO 8601 string). Finally, you call the encode() method with your object, which returns a Data object containing the UTF-8 encoded JSON or throws an error if it fails.
WHEN TO USE IT Use JSONEncoder whenever you need to serialize a Swift object into JSON. This is most common when making network requests, such as POSTing data to a web API. It's also useful for saving application state or user-generated content to a file on disk in a structured, portable format.
WHEN NOT TO USE IT For the reverse process—turning JSON data into Swift objects—you use its counterpart, JSONDecoder. If performance is absolutely critical for massive datasets, a more compact binary format like Protocol Buffers might be more efficient. JSONEncoder is specifically for creating JSON, not other data formats.
ONE CANONICAL EXAMPLE Imagine sending a new user's data to your server. You have a User struct conforming to Encodable. You create a JSONEncoder, set its keyEncodingStrategy to .convertToSnakeCase because your server expects keys like first_name. You then call encoder.encode(newUser). This transforms your User(firstName: "Alex") object into JSON data representing {"first_name": "Alex"}.
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.