Encode nil value as null with JSONEncoder
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Swift's synthesized Encodable implementation omits optional properties whose value is nil. If your API contract requires "field": null instead of omitting the key, you need to take control of encoding for that property and call encodeNil.
Why the default encoder omits nil
JSONEncoder does not have a global "encode all optionals as null" switch. When Swift synthesizes Encodable for a type, optional properties that are nil are usually skipped entirely.
That behavior is often fine, but some APIs distinguish between a missing field and a field explicitly set to null. In that case, omission and null are different signals, so the default synthesis is not enough.
Encode nil explicitly with a custom encode(to:)
The standard solution is to implement encode(to:) yourself and use encodeNil(forKey:) when the optional is absent.
The output contains nickname with a null value instead of omitting it.
Apply the same pattern selectively
You do not have to take over encoding for the whole type unless you want to. A custom encode(to:) method can still delegate ordinary fields to the keyed container and only special-case the optionals that must become null.
That makes the intent very clear. Fields that can be omitted keep the default-style behavior you choose to implement, while fields required by the server contract are always present.
When this matters in real APIs
Some backends interpret a missing field as "do not change this value" and null as "clear this value." Patch-style endpoints are a common example. In that situation, sending null intentionally is part of the protocol, not just a formatting preference.
This is why the correct answer is usually not "make JSONEncoder smarter." The correct answer is "encode the semantic difference explicitly where the API needs it."
The same approach works for nested models as well. If a nested object contains a few optional fields that must be emitted as null, custom encoding can live in that nested type without forcing every surrounding model to adopt special-case logic. Keeping the customization close to the field that needs it makes the serialization rules much easier to maintain.
That explicitness is valuable in API code reviews. Anyone reading the model can see immediately which fields are intentionally nullable in the wire format and which fields are simply absent when not provided. That is much easier to trust than relying on hidden serialization behavior.
Common Pitfalls
- Assuming
JSONEncoderhas a built-in strategy that converts everynilintonull. - Relying on synthesized
Encodablewhen the server requires the key to be present. - Overriding
encode(to:)and accidentally forgetting to encode one of the non-optional properties. - Treating omitted keys and
nullvalues as equivalent when the API contract distinguishes them. - Adding custom encoding everywhere when only one or two fields actually need explicit
null.
Summary
- Synthesized
Encodableusually omits optional properties whose value isnil. - To emit JSON
null, implementencode(to:)and callencodeNil(forKey:). - Use this pattern only for fields where the API contract truly requires explicit nulls.
- Missing keys and null values often carry different meanings on the server side.
- Manual encoding is the straightforward way to preserve that distinction.
Related reading
- Enterprise app deployment doesn't work on iOS 7.1
- Enterprise App Update Distribution on iOS 8
- Entitlements file was modified during the build, which is not supported
- Error-Handling in Swift-Language
- Error1, 0 Plugin with id ''com.android.application'' not found
- Error _handleNonLaunchSpecificActions in iOS9
- ERROR Android emulator gets killed in Android Studio
- Error ANDROID_HOME is not set and android command not in your PATH. You must fulfill at least one of these conditions.
.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.