How to serialize or convert Swift objects to JSON?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Converting Swift objects to JSON is a standard step for API requests, local caching, and event logging. The modern and safe approach is to model your data with Codable and encode with JSONEncoder instead of building JSON strings manually. This keeps type checks at compile time and makes failures easier to debug.
Start with Codable Models
The simplest path is to define your object as Codable, create a JSONEncoder, and encode to Data. You can then convert that data to a UTF-8 string for inspection or send it through URLSession.
This produces predictable output and avoids manual quoting mistakes. When objects grow over time, Codable keeps field mapping readable and testable.
Customize Keys, Dates, and Optional Fields
Real APIs often require snake case keys, ISO-8601 timestamps, and omission of null values. JSONEncoder supports these patterns directly.
With these settings, userId becomes user_id, dates use a standard timestamp format, and optional values are encoded according to model behavior. If an API has strict rules, this is far safer than post processing a JSON string.
Build HTTP Requests with Encoded JSON
A common endpoint workflow is encode your model, attach it to an HTTP request body, and set headers. Keep request assembly close to encoding so errors are easy to trace.
For production code, consider centralizing encoder configuration in one factory method. That ensures all endpoints share key and date rules.
Add Error Handling and Simple Tests
Encoding can fail when models include unsupported values or invalid custom logic. Catch errors at the boundary and return actionable context.
Unit tests should assert both success and formatting. For example, test that keys are converted to snake case when expected, and that date fields match the contract used by the backend.
Common Pitfalls
- Building JSON by string concatenation. This is fragile for quoting, escaping, and optional values.
- Forgetting consistent encoder configuration across endpoints. Create one shared encoder policy.
- Ignoring date formatting requirements. Agree on one date strategy with backend teams.
- Debugging from raw bytes only. Convert to UTF-8 string in logs for local inspection.
- Skipping error paths in tests. Add at least one failure test for custom encoding logic.
Summary
- Use
CodableandJSONEncoderas the default Swift JSON workflow. - Configure key strategy and date strategy explicitly for API compatibility.
- Attach encoded data directly to
URLRequestfor clean request construction. - Centralize encoding defaults to prevent contract drift.
- Add tests for both happy path and failure behavior.

