kotlinx.serialization throws MissingFieldException when a JSON key is absent and its property has no default. The usual fix is to add a default, like val pushEnabled: Boolean = true. That stops the crash. It also adds a second bug. That one shows up later, in the request body of a settings update. The default JSON settings skip any property whose value equals its default. So when a user turns push back on, pushEnabled = true matches the default. The field vanishes from the PATCH body. The server keeps its old false. The toggle flips back on the next load. Making the property nullable doesn’t fix the crash. Setting encodeDefaults = true for the whole Json instance fixes the toggle but can wipe other fields. The precise fix is a default for decoding plus @EncodeDefault on that one property. That way it’s always sent.
The settings screen that crashes on an older backend
The app adds a push toggle before every backend build sends the new field. Here’s the first model.
@Serializable
data class Settings(
val userId: String,
val pushEnabled: Boolean,
val digest: String,
)
// GET /settings from a backend build that predates pushEnabled
val json = """{"userId":"u1","digest":"weekly"}"""
Json.decodeFromString<Settings>(json)
We compiled it with Kotlin 2.4.20 and kotlinx-serialization-json 1.11.0 and ran it on the JVM. It failed straight away.
kotlinx.serialization.MissingFieldException: Field 'pushEnabled' is required for type with serial name 'Settings', but it was missing at path: $
The Kotlin serialization guide states the rule. An object decodes only when every property is in the input. A property becomes optional only when it has a default value. The type of the property doesn’t matter.
A nullable type alone still throws MissingFieldException
The first thing people try is val pushEnabled: Boolean?. It looks like it means “this can be absent.” We ran that version against the same JSON and got the same MissingFieldException. Nullability says the value may be null. Only a default says the key may be missing. So the working decode fix is val pushEnabled: Boolean = true, or Boolean? = null if “unknown” is a real state.
The other config flags don’t help here either. We decoded the same JSON with coerceInputValues = true and ignoreUnknownKeys = true. It still threw. The Json configuration page explains why. coerceInputValues covers only two cases, null sent for a non-nullable type and an unknown enum value. ignoreUnknownKeys handles extra keys in the input, not missing ones.
The default that fixed decoding drops the field from the PATCH
Now the backend ships the field. This user turned push off last month, so GET returns "pushEnabled":false. They flip it back on. The app sends a PATCH. The server changes only the keys present in the body.
@Serializable
data class Settings(
val userId: String,
val pushEnabled: Boolean = true,
val digest: String = "daily",
val quietHoursStart: String? = null,
)
suspend fun onPushToggled(current: Settings, enabled: Boolean) {
val body = Json.encodeToString(current.copy(pushEnabled = enabled))
api.patchSettings(body)
}
We replaced the API with a fake backend in plain Kotlin. It holds one row with pushEnabled=false and applies a PATCH key by key. Here’s what the app sent and what the server kept.
PATCH body: {"userId":"u1","digest":"weekly","quietHoursStart":"22:00"}
server pushEnabled: false
The body has no pushEnabled at all. The serialization guide documents this. By default, JSON serialization leaves out properties whose value equals the default. The encodeDefaults reference confirms it’s false by default. The library skips the value because a Kotlin decoder would fill it back in. A PATCH endpoint does the opposite. A missing key means “leave it as it is.”
So the bug only shows when the new value equals the default. Turning push off works, because false differs from the default. Turning it back on silently does nothing. The next GET returns false. The toggle jumps back. A test that only checks turning push off won’t catch it.
Turning on encodeDefaults everywhere wipes the fields you never loaded
The obvious next step is Json { encodeDefaults = true }. Now every property goes into the body. That fixes the toggle. It also turns a partial update into a full overwrite. Every field the client never received goes out as its default.
Defaults exist for exactly that case, a field the response didn’t include. We loaded the model from an endpoint that didn’t return quietHoursStart, then sent the toggle with encodeDefaults on.
encodeDefaults body: {"userId":"u1","pushEnabled":true,"digest":"weekly","quietHoursStart":null}
server quietHoursStart: null
Push was saved. The user’s quiet hours of 22:00 were cleared. The null appears because the explicitNulls setting is true by default, so null values are written out. Setting it to false keeps this null out of the body. The same configuration page warns it makes encoding and decoding asymmetrical.
Keep the default for decoding and add @EncodeDefault for sending
The default stays, because old responses still need it. One annotation then forces pushEnabled into every body.
@Serializable
data class Settings(
val userId: String,
@EncodeDefault val pushEnabled: Boolean = true, // always in the body
val digest: String = "daily",
val quietHoursStart: String? = null, // omitted while it's the default
)
// The shared Json instance keeps encodeDefaults = false.
suspend fun onPushToggled(current: Settings, enabled: Boolean) {
val body = Json.encodeToString(current.copy(pushEnabled = enabled))
api.patchSettings(body)
}
The @EncodeDefault reference says it controls one property, whatever the format settings are. Its mode defaults to ALWAYS. It doesn’t affect decoding. On 1.11.0 it compiled without an opt-in. We ran the fixed model through both earlier cases.
full GET: {"userId":"u1","pushEnabled":true,"digest":"weekly","quietHoursStart":"22:00"} -> push=true quiet="22:00"
partial GET: {"userId":"u1","pushEnabled":true,"digest":"weekly"} -> push=true quiet="22:00"
Push is saved in both. Quiet hours survive the partial load, because a null default is still left out. In practice, annotate the fields a PATCH must always carry. Keep encodeDefaults off on the shared instance. If an endpoint really is a full PUT, give it its own Json instance with encodeDefaults = true. Build it once, outside the call. The compiler warns that creating a Json per call is slow.
Teams often move to kotlinx.serialization after the Gson null fields in release builds bug. The Retrofit 204 crash post covers the response side of the same converter.
What to say when the interviewer shows you the stack trace
In a bug-squash round, the interviewer may show the MissingFieldException and ask for a fix. Adding the default is only half the answer. A strong answer covers both sides of that default.
- Read the message. Field
pushEnabledis in the class but absent from the JSON. It has no default. - Give the decode rule. Only a default makes a key optional.
Boolean?alone still throws. - Add the default, then say what it costs. With
encodeDefaults = false, a value equal to the default is never sent. - Connect it to the endpoint. A PATCH reads a missing key as “unchanged,” so turning push back on does nothing.
- Give the fix. Put
@EncodeDefaulton that property and keep the global setting off. - Name the test. Load
pushEnabled=false, set it to the default value and assert the body contains the key.
Answers that trade one bug for another
- “Make it nullable.” Our run still threw
MissingFieldException. A key becomes optional only with a default. - “Turn on
coerceInputValues.” It only covers anullfor a non-null type and unknown enum values. A missing key still throws. - “Turn on
ignoreUnknownKeys.” That handles extra keys in the input. Here a key is missing. - “Set
encodeDefaults = trueglobally.” The toggle works. Every partial update now overwrites fields with defaults. Our run cleared quiet hours. - “Catch the exception and show default settings.” The screen loads with values the user never chose. The next save sends them to the server.