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"}.
Interview question
Which task is the primary responsibility of JSONEncoder in a Swift application?
- a.Converting Swift objects into a standardized JSON format for external use.Correct
- b.Generating human-readable string representations of Swift objects for debugging.
- c.Facilitating the direct transmission of Swift objects over a network.
- d.Parsing incoming JSON data into native Swift data structures.
Why? this is the answer
JSONEncoder's fundamental purpose is to serialize Swift objects into JSON data, preparing them for tasks like sending to a server or saving to a file. It does not directly handle network transmission or the reverse process of parsing JSON.
Just read this? Test yourself on what you have been reading.
Read the original → developer.apple.com
- #ios
- #swift
- #codable
- #json
- #serialization
Put your scrolling time to good use
Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.
The iPhone app is on the way
We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.
Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.
We are hiring for this. Open roles that interview on ios — each one lists the topics its interview covers.
See open roles