Serialization: kotlinx vs Moshi
Why it matters
- A missing or extra JSON field is a common cause of crashes or wrong values after a server deploy. Knowing which library throws and which silently fills a value decides whether you see the bug in a crash dashboard or in a support ticket.
- Interviewers at mid-to-senior level ask you to compare converters, explain null-safety, and show a working Retrofit setup, with the exact annotation, configuration flag and exception type.
- kotlinx.serialization is multiplatform and is the default for Ktor; Moshi is JVM-only and is usually used with Retrofit. Choosing affects whether your models can move to a KMP module later.
- Every networking lesson in this module (Retrofit, Ktor, caching, error handling) assumes you can turn a response body into a typed object without losing data.
The simple explanation
- A JSON response is a form letter from the server.
- A required field with no default is a mandatory field: if it is missing, the form is rejected (
MissingFieldException). - A field with a default is a pre-filled field: if the server omits it, you keep the pre-filled value.
ignoreUnknownKeys = truemeans you ignore handwritten notes on the form that you do not recognise.- Gson is a clerk who, for many Kotlin classes, writes 0, false or nothing into every blank box without telling you, even in boxes marked "required".
When Retrofit receives a response body, it asks its converter factories, in the order you added them, for a converter for the declared return type. The first factory that accepts the type turns the bytes into your object.
kotlinx.serialization: mark the class with @Serializable. The Kotlin serialization compiler plugin generates a KSerializer for it at compile time; no reflection is used. A Json instance, configured with Json { ... }, uses that serializer to decode. Useful flags:
ignoreUnknownKeys = true: skip JSON keys that have no matching property. Defaultfalse: an unknown key throwsSerializationException.coerceInputValues = true: a JSONnullfor a non-null property with a default, or an unknown enum value, uses the default instead of throwing.explicitNulls = false: null properties are left out when encoding, and a missing key for a nullable property is decoded asnulleven without a default. Defaulttrue.encodeDefaults: defaultfalse, so properties that still hold their default value are not written when you encode. Set it totrueif the server needs every field.
A property without a default is required: if the key is missing, decoding throws MissingFieldException. A property with a default (val count: Int = 0) uses that default when the key is absent.
Moshi (Square): mark the class with @JsonClass(generateAdapter = true) and add the moshi-kotlin-codegen processor (with KSP) to generate adapters at compile time, or add KotlinJsonAdapterFactory from moshi-kotlin, which uses kotlin-reflect at runtime. Unknown keys are ignored by default. A missing non-null property without a default throws JsonDataException; Kotlin defaults are respected. Moshi is JVM-only.
Gson (Google) does not understand Kotlin. If the class has no no-arg constructor, Gson creates the object without running any constructor, so missing fields get JVM zero values: 0 for Int, false for Boolean, and null even for a non-null String. Kotlin default values are skipped too. The null in a non-null property crashes later with a NullPointerException far from the parsing code. (If every constructor parameter has a default, Kotlin generates a no-arg constructor and Gson uses it, so the defaults apply.)
| Feature | kotlinx.serialization | Moshi (codegen) | Gson |
|---|---|---|---|
| Platform | Multiplatform | JVM / Android | JVM / Android |
| Adapter creation | Compiler plugin, compile time | KSP processor, compile time | Reflection at runtime |
| Unknown keys | Throws unless ignoreUnknownKeys = true | Ignored | Ignored |
| Missing non-null field without default | MissingFieldException | JsonDataException | JVM zero value (0, false, null) |
| Kotlin default values | Used | Used | Skipped unless there is a no-arg constructor |
| Retrofit converter | json.asConverterFactory(mediaType) | MoshiConverterFactory.create(moshi) | GsonConverterFactory.create() |
In the error-handling lesson you will map SerializationException (and its subclass MissingFieldException) into a sealed result type.
Notes
@Serializableneeds the Kotlin serialization compiler plugin (org.jetbrains.kotlin.plugin.serialization, same version as Kotlin). Without it no serializer is generated and decoding fails at runtime withSerializationException: Serializer for class ... is not found.- Turn on
ignoreUnknownKeys = truein theJsoninstance used for server responses. Without it, one new server field breaks every app version that does not know it. - A property with a default (
val count: Int = 0) is optional when decoding. A property without a default is required and throwsMissingFieldExceptionwhen absent. - A JSON
nullfor a non-null property throws in kotlinx.serialization, even if the property has a default, unlesscoerceInputValues = true. - Moshi codegen (
@JsonClass(generateAdapter = true)with KSP) generates adapters at compile time.KotlinJsonAdapterFactoryuses kotlin-reflect at runtime: it adds the reflect library, is slower on first use, and needs R8 keep rules. Prefer codegen. - Gson without a no-arg constructor fills missing fields with
0,falseandnulland ignores Kotlin defaults. A missingverified: Booleanbecomesfalse, and a missingname: Stringbecomesnulldespite the non-null type. - In Retrofit, the converter is added once with
addConverterFactory. For kotlinx.serialization usejson.asConverterFactory("application/json".toMediaType())fromcom.squareup.retrofit2:converter-kotlinx-serialization. The media type is theContent-Typeused for request bodies you send. - Create one
JsonorMoshiinstance and reuse it. Both cache serializers or adapters internally, and a new instance per request repeats that work. - Parse errors are not network errors. kotlinx.serialization throws
SerializationException(anIllegalArgumentException), Moshi throwsJsonDataExceptionfor wrong or missing values andJsonEncodingException(anIOException) for malformed JSON. Map them to their own error type and do not retry them.
Code example
This shows a @Serializable model with required and optional fields, a Json instance configured for server responses, and the same Json wired into Retrofit.
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
import retrofit2.Retrofit
import retrofit2.converter.kotlinx.serialization.asConverterFactory
@Serializable
data class User(
@SerialName("user_id") val id: Long, // required: no default
val name: String, // required: no default
val email: String? = null, // optional: null when absent
val verified: Boolean = false, // optional: false when absent
val tags: List<String> = emptyList() // optional: empty when absent
)
// One Json instance, shared across the app (provide it as a singleton).
val json = Json {
ignoreUnknownKeys = true // a new server field does not break old app versions
coerceInputValues = true // "tags": null falls back to emptyList()
}
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
.build()
// In a Retrofit interface:
// @GET("users/{id}") suspend fun getUser(@Path("id") id: Long): User
//
// Body lacks "user_id" -> MissingFieldException
// Body lacks "email" -> email = null
// Body has "avatar_url" -> ignored (ignoreUnknownKeys)The same model with Moshi codegen, for comparison:
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.squareup.moshi.Moshi
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
@JsonClass(generateAdapter = true) // adapter generated by moshi-kotlin-codegen via KSP
data class UserDto(
@Json(name = "user_id") val id: Long,
val name: String,
val email: String? = null,
val verified: Boolean = false,
)
val moshi: Moshi = Moshi.Builder().build() // generated adapters are found automatically
val moshiRetrofit: Retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build()@SerialName("user_id")(kotlinx) and@Json(name = "user_id")(Moshi) map a property to a different JSON key.- Unknown keys are ignored by Moshi without any flag; kotlinx.serialization needs
ignoreUnknownKeys = true. - Both libraries throw when
user_idornameis missing, and both use the Kotlin defaults foremailandverified.
Run the idea in plain Kotlin
This models how a strict decoder (kotlinx.serialization), the ignoreUnknownKeys flag, and a Gson-style decoder that skips the constructor treat the same JSON.
class MissingFieldException(field: String) : Exception("Field '" + field + "' is required but it was missing")
class UnknownKeyException(key: String) : Exception("Encountered an unknown key '" + key + "'")
object NoDefault
// Product(id: Long, title: String, inStock: Boolean = true, labels: List<String> = emptyList())
data class Field(val name: String, val default: Any?)
val productFields = listOf(
Field("id", NoDefault),
Field("title", NoDefault),
Field("inStock", true),
Field("labels", emptyList<String>()),
)
fun decodeLikeKotlinx(json: Map<String, Any?>, ignoreUnknownKeys: Boolean): Map<String, Any?> {
val known = productFields.map { it.name }.toSet()
if (!ignoreUnknownKeys) {
json.keys.firstOrNull { it !in known }?.let { throw UnknownKeyException(it) }
}
return productFields.associate { f ->
f.name to when {
json.containsKey(f.name) -> json[f.name]
f.default != NoDefault -> f.default
else -> throw MissingFieldException(f.name)
}
}
}
// Gson without a no-arg constructor: no constructor runs, so missing fields get JVM zero values
fun jvmZero(name: String): Any? = when (name) {
"id" -> 0L
"inStock" -> false
else -> null
}
fun decodeLikeGson(json: Map<String, Any?>): Map<String, Any?> =
productFields.associate { f -> f.name to (if (json.containsKey(f.name)) json[f.name] else jvmZero(f.name)) }
fun main() {
val body = mapOf("id" to 42L, "title" to "Widget", "color" to "red")
try {
decodeLikeKotlinx(body, ignoreUnknownKeys = false)
} catch (e: Exception) {
println("strict: " + e.message)
}
println("ignoreUnknownKeys: " + decodeLikeKotlinx(body, ignoreUnknownKeys = true))
val partial = mapOf("id" to 7L)
try {
decodeLikeKotlinx(partial, ignoreUnknownKeys = true)
} catch (e: Exception) {
println("missing: " + e.message)
}
println("gson-style: " + decodeLikeGson(partial))
println("title is a non-null String in Kotlin, but Gson stored null")
}Expected output:
strict: Encountered an unknown key 'color'
ignoreUnknownKeys: {id=42, title=Widget, inStock=true, labels=[]}
missing: Field 'title' is required but it was missing
gson-style: {id=7, title=null, inStock=false, labels=null}
title is a non-null String in Kotlin, but Gson stored null
In production
- After a backend deploy added a
regionstring to the user response, the crash dashboard showed a spike inSerializationExceptionfrom the profile screen. - The
Jsoninstance was created with default settings, soignoreUnknownKeyswasfalse. - The repository caught only
IOExceptionandHttpException.SerializationExceptionis neither, so it escaped theviewModelScope.launchand crashed the app.
- Reproduced the crash in a unit test by decoding a JSON string with an extra
"region": "EU"key using the sharedJsoninstance. - Set
ignoreUnknownKeys = trueon the sharedJsonsingleton and kept the test with unknown keys as a regression test. - Mapped
SerializationExceptionto a parse error state in the repository, so a future contract break shows an error screen instead of crashing.
- Support tickets reported that verified users saw an "unverified" badge on the profile screen.
- A legacy endpoint sometimes omitted the
verifiedfield. - The model was parsed with Gson and had no no-arg constructor, so the missing
Booleanbecamefalse. No crash, no log, just the wrong value.
- Reproduced by calling the legacy endpoint and printing the raw JSON; the
verifiedkey was absent. - Migrated the model to kotlinx.serialization with
val verified: Boolean? = null, so "not sent" is different fromfalse, and the UI hides the badge (and logs the case) when it isnull. - Asked the backend to always send
verified, and added a contract test against a recorded response that fails if the key disappears.
Common mistakes
- Forgetting ignoreUnknownKeys. Without it, a new server field throws
SerializationExceptionin every app version that does not know it. Set it on theJsoninstance used for responses and keep a test with extra keys. - Trusting Gson with Kotlin types. Gson can put
nullinto a non-nullStringandfalseinto a missingBoolean, and it skips Kotlin defaults. Use kotlinx.serialization or Moshi, and use a nullable type when "absent" must be visible. - Using a default that hides missing data.
val verified: Boolean = falseturns "not sent" into "false". Use a default only when it is a correct value, and a nullable type or a required field otherwise. - Missing the compiler plugin.
@Serializablewithout the serialization plugin generates nothing, and decoding fails at runtime with "Serializer for class ... is not found". Add the plugin; a runtime dependency alone is not enough. - Using Moshi reflection instead of codegen.
KotlinJsonAdapterFactorypulls in kotlin-reflect, is slower on first use, and needs R8 keep rules.@JsonClass(generateAdapter = true)with KSP generates adapters at compile time. - Treating parse errors as network errors. A malformed or mismatched body is a contract bug. Mapping it to "no connection" and retrying with backoff just repeats the failure. Note that Moshi's
JsonEncodingExceptionis anIOException, so a plaincatch (e: IOException)will mislabel it.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What happens when the server adds a new field to a JSON response?”
“Why do teams migrate from Gson to kotlinx.serialization or Moshi?”
“How do you wire kotlinx.serialization into Retrofit?”
“What is the null-safety problem with Gson and how does kotlinx.serialization solve it?”
Quiz
What does kotlinx.serialization do when a required property (no default) is missing from the JSON?
Which Json setting prevents a new, unknown server field from failing decoding?
Gson parses JSON without a verified key into data class User(val name: String, val verified: Boolean), which has no no-arg constructor. What is verified?
Which Moshi setup generates adapters at compile time?
0 of 4 answered
Mini task
15-minute exercise: default values and unknown keys
-
In your Android project add
org.jetbrains.kotlinx:kotlinx-serialization-json:1.13.0and, for Retrofit,com.squareup.retrofit2:converter-kotlinx-serialization:3.0.0. Apply the pluginorg.jetbrains.kotlin.plugin.serializationwith the same version as your Kotlin plugin. -
Create a data class
Productwith@Serializable:@SerialName("product_id") val id: Long(required, no default)val title: String(required, no default)val price: Double = 0.0(optional, default)val inStock: Boolean = true(optional, default)val labels: List<String> = emptyList()(optional, default)
-
Create a
Jsoninstance withignoreUnknownKeys = true. -
Write a unit test that decodes this JSON string with
json.decodeFromString<Product>(...):{ "product_id": 42, "title": "Widget", "color": "red" }Note thatprice,inStockandlabelsare absent, andcoloris an unknown key. -
Print the resulting
Product. Confirm thatpriceis0.0,inStockistrue,labelsis empty, and no exception is thrown forcolor. -
Remove the default from
price(make itval price: Double). Run the same test. Confirm you get aMissingFieldException. -
Put the default back. Now remove
ignoreUnknownKeys = true. Run the test. Confirm you get aSerializationExceptionmentioning the unknown keycolor. -
Decode
{ "product_id": 42, "title": "Widget", "labels": null }and confirm it throws; then addcoerceInputValues = trueand confirmlabelsbecomes empty.
Done condition: You have seen four outcomes: a successful parse with defaults and an ignored unknown key, MissingFieldException for a required field, SerializationException for an unknown key when ignoreUnknownKeys is off, and a JSON null coerced to the default. You can explain each in one sentence.