How to serialize or convert Swift objects to JSON?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
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.
Related reading
- How to set -source 1.7 in Android Studio and Gradle
- How to set a bitmap from resource
- How to Set a Custom Font in the ActionBar Title?
- How to set a timeout with AFNetworking
- How to set ANDROID_HOME path in ubuntu?
- How to set back button text in iOS navigation controller?
- How to set background color of a View
- How to set build and version number of Flutter app
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.