{"id":928,"date":"2026-10-29T13:48:00","date_gmt":"2026-10-29T12:48:00","guid":{"rendered":"https:\/\/grindloop.ai\/blog\/?p=928"},"modified":"2026-10-28T22:20:46","modified_gmt":"2026-10-28T21:20:46","slug":"kotlinx-serialization-missingfieldexception-default","status":"publish","type":"post","link":"https:\/\/grindloop.ai\/blog\/kotlinx-serialization-missingfieldexception-default\/","title":{"rendered":"MissingFieldException in kotlinx.serialization: Why the Default You Add Drops the Field From Your PATCH"},"content":{"rendered":"<p>kotlinx.serialization throws <code>MissingFieldException<\/code> when a JSON key is absent and its property has no default. The usual fix is to add a default, like <code>val pushEnabled: Boolean = true<\/code>. 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, <code>pushEnabled = true<\/code> matches the default. The field vanishes from the PATCH body. The server keeps its old <code>false<\/code>. The toggle flips back on the next load. Making the property nullable doesn&#8217;t fix the crash. Setting <code>encodeDefaults = true<\/code> for the whole <code>Json<\/code> instance fixes the toggle but can wipe other fields. The precise fix is a default for decoding plus <code>@EncodeDefault<\/code> on that one property. That way it&#8217;s always sent.<\/p>\n\n<h2>The settings screen that crashes on an older backend<\/h2>\n\n<p>The app adds a push toggle before every backend build sends the new field. Here&#8217;s the first model.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">@Serializable\ndata class Settings(\n    val userId: String,\n    val pushEnabled: Boolean,\n    val digest: String,\n)\n\n\/\/ GET \/settings from a backend build that predates pushEnabled\nval json = \"\"\"{\"userId\":\"u1\",\"digest\":\"weekly\"}\"\"\"\nJson.decodeFromString&lt;Settings&gt;(json)<\/pre>\n\n\n<p>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.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">kotlinx.serialization.MissingFieldException: Field 'pushEnabled' is required for type with serial name 'Settings', but it was missing at path: $<\/pre>\n\n\n<p>The <a href=\"https:\/\/kotlinlang.org\/docs\/serialization-customization-options.html\" target=\"_blank\" rel=\"noopener\">Kotlin serialization guide<\/a> 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&#8217;t matter.<\/p>\n\n<h2>A nullable type alone still throws MissingFieldException<\/h2>\n\n<p>The first thing people try is <code>val pushEnabled: Boolean?<\/code>. It looks like it means &#8220;this can be absent.&#8221; We ran that version against the same JSON and got the same <code>MissingFieldException<\/code>. Nullability says the value may be <code>null<\/code>. Only a default says the key may be missing. So the working decode fix is <code>val pushEnabled: Boolean = true<\/code>, or <code>Boolean? = null<\/code> if &#8220;unknown&#8221; is a real state.<\/p>\n\n<p>The other config flags don&#8217;t help here either. We decoded the same JSON with <code>coerceInputValues = true<\/code> and <code>ignoreUnknownKeys = true<\/code>. It still threw. The <a href=\"https:\/\/kotlinlang.org\/docs\/serialization-json-configuration.html\" target=\"_blank\" rel=\"noopener\">Json configuration page<\/a> explains why. <code>coerceInputValues<\/code> covers only two cases, <code>null<\/code> sent for a non-nullable type and an unknown enum value. <code>ignoreUnknownKeys<\/code> handles extra keys in the input, not missing ones.<\/p>\n\n<h2>The default that fixed decoding drops the field from the PATCH<\/h2>\n\n<p>Now the backend ships the field. This user turned push off last month, so GET returns <code>\"pushEnabled\":false<\/code>. They flip it back on. The app sends a PATCH. The server changes only the keys present in the body.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">@Serializable\ndata class Settings(\n    val userId: String,\n    val pushEnabled: Boolean = true,\n    val digest: String = \"daily\",\n    val quietHoursStart: String? = null,\n)\n\nsuspend fun onPushToggled(current: Settings, enabled: Boolean) {\n    val body = Json.encodeToString(current.copy(pushEnabled = enabled))\n    api.patchSettings(body)\n}<\/pre>\n\n\n<p>We replaced the API with a fake backend in plain Kotlin. It holds one row with <code>pushEnabled=false<\/code> and applies a PATCH key by key. Here&#8217;s what the app sent and what the server kept.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">PATCH body: {\"userId\":\"u1\",\"digest\":\"weekly\",\"quietHoursStart\":\"22:00\"}\nserver pushEnabled: false<\/pre>\n\n\n<p>The body has no <code>pushEnabled<\/code> at all. The serialization guide documents this. By default, JSON serialization leaves out properties whose value equals the default. The <a href=\"https:\/\/kotlinlang.org\/api\/kotlinx.serialization\/kotlinx-serialization-json\/kotlinx.serialization.json\/-json-builder\/encode-defaults.html\" target=\"_blank\" rel=\"noopener\"><code>encodeDefaults<\/code> reference<\/a> confirms it&#8217;s <code>false<\/code> 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 &#8220;leave it as it is.&#8221;<\/p>\n\n<p>So the bug only shows when the new value equals the default. Turning push off works, because <code>false<\/code> differs from the default. Turning it back on silently does nothing. The next GET returns <code>false<\/code>. The toggle jumps back. A test that only checks turning push off won&#8217;t catch it.<\/p>\n\n<h2>Turning on encodeDefaults everywhere wipes the fields you never loaded<\/h2>\n\n<p>The obvious next step is <code>Json { encodeDefaults = true }<\/code>. 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.<\/p>\n\n<p>Defaults exist for exactly that case, a field the response didn&#8217;t include. We loaded the model from an endpoint that didn&#8217;t return <code>quietHoursStart<\/code>, then sent the toggle with <code>encodeDefaults<\/code> on.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">encodeDefaults body: {\"userId\":\"u1\",\"pushEnabled\":true,\"digest\":\"weekly\",\"quietHoursStart\":null}\nserver quietHoursStart: null<\/pre>\n\n\n<p>Push was saved. The user&#8217;s quiet hours of 22:00 were cleared. The <code>null<\/code> appears because the <code>explicitNulls<\/code> setting is <code>true<\/code> by default, so null values are written out. Setting it to <code>false<\/code> keeps this <code>null<\/code> out of the body. The same configuration page warns it makes encoding and decoding asymmetrical.<\/p>\n\n<h2>Keep the default for decoding and add @EncodeDefault for sending<\/h2>\n\n<p>The default stays, because old responses still need it. One annotation then forces <code>pushEnabled<\/code> into every body.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">@Serializable\ndata class Settings(\n    val userId: String,\n    @EncodeDefault val pushEnabled: Boolean = true,  \/\/ always in the body\n    val digest: String = \"daily\",\n    val quietHoursStart: String? = null,             \/\/ omitted while it's the default\n)\n\n\/\/ The shared Json instance keeps encodeDefaults = false.\nsuspend fun onPushToggled(current: Settings, enabled: Boolean) {\n    val body = Json.encodeToString(current.copy(pushEnabled = enabled))\n    api.patchSettings(body)\n}<\/pre>\n\n\n<p>The <a href=\"https:\/\/kotlinlang.org\/api\/kotlinx.serialization\/kotlinx-serialization-core\/kotlinx.serialization\/-encode-default\/\" target=\"_blank\" rel=\"noopener\"><code>@EncodeDefault<\/code> reference<\/a> says it controls one property, whatever the format settings are. Its mode defaults to <code>ALWAYS<\/code>. It doesn&#8217;t affect decoding. On 1.11.0 it compiled without an opt-in. We ran the fixed model through both earlier cases.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">full GET:    {\"userId\":\"u1\",\"pushEnabled\":true,\"digest\":\"weekly\",\"quietHoursStart\":\"22:00\"} -> push=true quiet=\"22:00\"\npartial GET: {\"userId\":\"u1\",\"pushEnabled\":true,\"digest\":\"weekly\"} -> push=true quiet=\"22:00\"<\/pre>\n\n\n<p>Push is saved in both. Quiet hours survive the partial load, because a <code>null<\/code> default is still left out. In practice, annotate the fields a PATCH must always carry. Keep <code>encodeDefaults<\/code> off on the shared instance. If an endpoint really is a full PUT, give it its own <code>Json<\/code> instance with <code>encodeDefaults = true<\/code>. Build it once, outside the call. The compiler warns that creating a <code>Json<\/code> per call is slow.<\/p>\n\n<p>Teams often move to kotlinx.serialization after the <a href=\"https:\/\/grindloop.ai\/blog\/gson-null-fields-release-build\/\">Gson null fields in release builds<\/a> bug. The <a href=\"https:\/\/grindloop.ai\/blog\/retrofit-204-null-body-crash\/\">Retrofit 204 crash<\/a> post covers the response side of the same converter.<\/p>\n\n<h2>What to say when the interviewer shows you the stack trace<\/h2>\n\n<p>In a bug-squash round, the interviewer may show the <code>MissingFieldException<\/code> and ask for a fix. Adding the default is only half the answer. A strong answer covers both sides of that default.<\/p>\n\n<ol>\n<li>Read the message. Field <code>pushEnabled<\/code> is in the class but absent from the JSON. It has no default.<\/li>\n<li>Give the decode rule. Only a default makes a key optional. <code>Boolean?<\/code> alone still throws.<\/li>\n<li>Add the default, then say what it costs. With <code>encodeDefaults = false<\/code>, a value equal to the default is never sent.<\/li>\n<li>Connect it to the endpoint. A PATCH reads a missing key as &#8220;unchanged,&#8221; so turning push back on does nothing.<\/li>\n<li>Give the fix. Put <code>@EncodeDefault<\/code> on that property and keep the global setting off.<\/li>\n<li>Name the test. Load <code>pushEnabled=false<\/code>, set it to the default value and assert the body contains the key.<\/li>\n<\/ol>\n\n<h2>Answers that trade one bug for another<\/h2>\n\n<ul>\n<li>&#8220;Make it nullable.&#8221; Our run still threw <code>MissingFieldException<\/code>. A key becomes optional only with a default.<\/li>\n<li>&#8220;Turn on <code>coerceInputValues<\/code>.&#8221; It only covers a <code>null<\/code> for a non-null type and unknown enum values. A missing key still throws.<\/li>\n<li>&#8220;Turn on <code>ignoreUnknownKeys<\/code>.&#8221; That handles extra keys in the input. Here a key is missing.<\/li>\n<li>&#8220;Set <code>encodeDefaults = true<\/code> globally.&#8221; The toggle works. Every partial update now overwrites fields with defaults. Our run cleared quiet hours.<\/li>\n<li>&#8220;Catch the exception and show default settings.&#8221; The screen loads with values the user never chose. The next save sends them to the server.<\/li>\n<\/ul>","protected":false},"excerpt":{"rendered":"<p>MissingFieldException in kotlinx.serialization? A default fixes decoding but drops the field from PATCH bodies. Runnable repro and the @EncodeDefault fix.<\/p>\n","protected":false},"author":2,"featured_media":930,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"rank_math_title":"MissingFieldException in kotlinx.serialization: Why the Default You Add Drops the Field From Your PATCH","rank_math_description":"MissingFieldException in kotlinx.serialization? A default fixes decoding but drops the field from PATCH bodies. Runnable repro and the @EncodeDefault fix.","rank_math_focus_keyword":"missingfieldexception","footnotes":""},"categories":[9,6],"tags":[15,87,16,12,112,57,45],"class_list":["post-928","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-bug-squash","category-networking","tag-android","tag-debugging-interview","tag-interview-prep","tag-kotlin","tag-kotlinx-serialization","tag-networking","tag-technical-interview"],"_links":{"self":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/928","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/comments?post=928"}],"version-history":[{"count":1,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/928\/revisions"}],"predecessor-version":[{"id":929,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/928\/revisions\/929"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media\/930"}],"wp:attachment":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media?parent=928"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/categories?post=928"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/tags?post=928"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}