Serialization: kotlinx vs Moshi

Compare kotlinx.serialization and Moshi for Android JSON, see why Gson breaks Kotlin null safety, and configure both so server changes do not crash. About 25 minutes.

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 = true means 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. Default false: an unknown key throws SerializationException.
  • coerceInputValues = true: a JSON null for 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 as null even without a default. Default true.
  • encodeDefaults: default false, so properties that still hold their default value are not written when you encode. Set it to true if 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.)

Featurekotlinx.serializationMoshi (codegen)Gson
PlatformMultiplatformJVM / AndroidJVM / Android
Adapter creationCompiler plugin, compile timeKSP processor, compile timeReflection at runtime
Unknown keysThrows unless ignoreUnknownKeys = trueIgnoredIgnored
Missing non-null field without defaultMissingFieldExceptionJsonDataExceptionJVM zero value (0, false, null)
Kotlin default valuesUsedUsedSkipped unless there is a no-arg constructor
Retrofit converterjson.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

  • @Serializable needs 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 with SerializationException: Serializer for class ... is not found.
  • Turn on ignoreUnknownKeys = true in the Json instance 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 throws MissingFieldException when absent.
  • A JSON null for a non-null property throws in kotlinx.serialization, even if the property has a default, unless coerceInputValues = true.
  • Moshi codegen (@JsonClass(generateAdapter = true) with KSP) generates adapters at compile time. KotlinJsonAdapterFactory uses 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, false and null and ignores Kotlin defaults. A missing verified: Boolean becomes false, and a missing name: String becomes null despite the non-null type.
  • In Retrofit, the converter is added once with addConverterFactory. For kotlinx.serialization use json.asConverterFactory("application/json".toMediaType()) from com.squareup.retrofit2:converter-kotlinx-serialization. The media type is the Content-Type used for request bodies you send.
  • Create one Json or Moshi instance 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 (an IllegalArgumentException), Moshi throws JsonDataException for wrong or missing values and JsonEncodingException (an IOException) 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_id or name is missing, and both use the Kotlin defaults for email and verified.

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

Server added a field, crash spike reported
  • After a backend deploy added a region string to the user response, the crash dashboard showed a spike in SerializationException from the profile screen.
  • The Json instance was created with default settings, so ignoreUnknownKeys was false.
  • The repository caught only IOException and HttpException. SerializationException is neither, so it escaped the viewModelScope.launch and crashed the app.
The fix
  • Reproduced the crash in a unit test by decoding a JSON string with an extra "region": "EU" key using the shared Json instance.
  • Set ignoreUnknownKeys = true on the shared Json singleton and kept the test with unknown keys as a regression test.
  • Mapped SerializationException to a parse error state in the repository, so a future contract break shows an error screen instead of crashing.
Verified users shown as unverified
  • Support tickets reported that verified users saw an "unverified" badge on the profile screen.
  • A legacy endpoint sometimes omitted the verified field.
  • The model was parsed with Gson and had no no-arg constructor, so the missing Boolean became false. No crash, no log, just the wrong value.
The fix
  • Reproduced by calling the legacy endpoint and printing the raw JSON; the verified key was absent.
  • Migrated the model to kotlinx.serialization with val verified: Boolean? = null, so "not sent" is different from false, and the UI hides the badge (and logs the case) when it is null.
  • 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 SerializationException in every app version that does not know it. Set it on the Json instance used for responses and keep a test with extra keys.
  • Trusting Gson with Kotlin types. Gson can put null into a non-null String and false into a missing Boolean, 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 = false turns "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. @Serializable without 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. KotlinJsonAdapterFactory pulls 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 JsonEncodingException is an IOException, so a plain catch (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

  1. In your Android project add org.jetbrains.kotlinx:kotlinx-serialization-json:1.13.0 and, for Retrofit, com.squareup.retrofit2:converter-kotlinx-serialization:3.0.0. Apply the plugin org.jetbrains.kotlin.plugin.serialization with the same version as your Kotlin plugin.

  2. Create a data class Product with @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)
  3. Create a Json instance with ignoreUnknownKeys = true.

  4. Write a unit test that decodes this JSON string with json.decodeFromString<Product>(...): { "product_id": 42, "title": "Widget", "color": "red" } Note that price, inStock and labels are absent, and color is an unknown key.

  5. Print the resulting Product. Confirm that price is 0.0, inStock is true, labels is empty, and no exception is thrown for color.

  6. Remove the default from price (make it val price: Double). Run the same test. Confirm you get a MissingFieldException.

  7. Put the default back. Now remove ignoreUnknownKeys = true. Run the test. Confirm you get a SerializationException mentioning the unknown key color.

  8. Decode { "product_id": 42, "title": "Widget", "labels": null } and confirm it throws; then add coerceInputValues = true and confirm labels becomes 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.

Next: Error handling and result types