kotlinx.serialization vs Gson

Networking Mid-level Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Predict the output

The JSON has an extra field "age". What happens?

@Serializable
data class Profile(val name: String, val premium: Boolean = false)

fun main() {
    val json = """{"name":"Ana","age":31}"""
    val strict = runCatching { Json.decodeFromString<Profile>(json) }
    val lenient = Json { ignoreUnknownKeys = true }.decodeFromString<Profile>(json)
    println("${strict.isFailure} $lenient")
}
Options
Hint 1 of 1

What is the default for ignoreUnknownKeys?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A true Profile(name=Ana, premium=false)

Correct. The default Json rejects unknown keys; the lenient one ignores age and uses the default for premium.

Why not the others?
  • B false Profile(name=Ana, premium=false). By default, unknown keys are an error.
  • C true Profile(name=Ana, premium=null). premium has a default, so it's false.
  • D It doesn't compile. This is valid kotlinx.serialization code.

30-second answer

Gson uses reflection and doesn't understand Kotlin's null safety or default values: a missing field can leave a non-null property null, causing crashes far from the parsing code. kotlinx.serialization generates serializers at compile time with @Serializable, respects defaults and nullability, works in Multiplatform code and needs no reflection rules for R8. Moshi with codegen is another Kotlin-aware choice.

Practise saying it · 30 s. No recording, just a timer

Compare kotlinx.serialization and Gson.

Say your answer out loud, then check which of these points you covered:

  • Gson ignores Kotlin null safety
  • Compile-time serializers
  • Defaults and ignoreUnknownKeys
  • No reflection for R8

Deep dive

Json { ignoreUnknownKeys = true } keeps old app versions working when the API adds fields.

Default values make missing fields safe; coerceInputValues turns invalid enum values into defaults.

@SerialName maps JSON names to Kotlin names.

Polymorphic sealed classes use a class discriminator field.

Common mistakes

  • Using Gson with Kotlin data classes and non-null fields.
  • Not setting ignoreUnknownKeys and breaking on new API fields.
  • Keeping Gson model classes unobfuscated with broad keep rules.

Senior take & follow-ups

Explain the null-safety hole in Gson concretely.

Follow-up questions

Think of your answer first, then open the hint.

  1. What happens with a missing non-null field in Gson?

    Show hint

    The property ends up null despite its type.

  2. Why does kotlinx.serialization help R8?

    Show hint

    No reflection, so no keep rules for models.

Compare on iOS: Codable and mismatched keys Codable is Swift's compile-time equivalent.

Suggest a fix if something here is wrong or out of date.