With Retrofit and GsonConverterFactory, why can a missing JSON field leave a non-null Kotlin property null, and where does it fail?
answer
- reflection ignores Kotlin's type system
- constructor never runs
- JVM defaults: null and 0
- success now, crash later
basics
~20 sGson's reflective adapter can create the object without running its Kotlin constructor, so a missing field keeps the JVM default: null even for a non-null String. Retrofit reports success, and the NullPointerException surfaces later, wherever the property is first used.
solid answer
~40 s`GsonConverterFactory` hands the body to Gson's reflection-based adapter, which knows nothing about Kotlin nullability. When the class has no no-argument constructor, Gson allocates the instance without calling a constructor, so the null checks and default values Kotlin compiles into it never run: a missing `name: String` stays null and a missing `Int` becomes 0. The converter returns normally, so the call succeeds and neither `HttpException` nor `IOException` appears. The `NullPointerException` fires later, in a mapper or a composable, far from the network layer. A Kotlin-aware converter fails inside `convert()` instead: kotlinx.serialization's `asConverterFactory()` throws for a missing field with no default, as does Moshi when the instance given to `MoshiConverterFactory.create(moshi)` has Kotlin support. Retrofit rethrows that runtime exception from the call, where your error handling sits.
code
kotlin · 12 linesdata class User(val id: Long, val name: String)
interface UserApi {
@GET("users/{id}")
suspend fun user(@Path("id") id: Long): User
}
// The server responds {"id": 7} with no "name".
suspend fun nameLength(api: UserApi): Int {
val user = api.user(7) // returns normally under GsonConverterFactory
return user.name.length // NullPointerException is thrown here
}go deeper
Recall that a reflection-based converter like Gson can put null into a Kotlin property declared non-null.
Explain why: Gson may skip the Kotlin constructor, so null checks and defaults never run, and primitives silently become 0.
Trace where the crash surfaces, outside the call's error handling, and show how a Kotlin-aware converter moves the failure into convert().
Weigh retiring the reflection-based converter: the migration cost per endpoint against crashes that never show up as network errors.
## What the converter actually does `GsonConverterFactory` is a thin bridge. For a response type it asks the `Gson` instance for a type adapter, reads the body with it, checks that the whole JSON document was consumed, and returns the result. Retrofit adds **no validation of its own**: whatever object the adapter builds is what your suspend method returns. So when a field is missing, the question is entirely what Gson's adapter does, and Retrofit reports the outcome as a successful call. ## Why Kotlin's guarantees are bypassed Gson's default adapter for a class is **reflection-based**: it finds the class's fields and assigns them from matching JSON names. Kotlin's null-safety and default arguments live in the class's constructor, and Gson often never calls it. - If the class has **no no-argument constructor** (a typical `data class User(val id: Long, val name: String)`), Gson creates the instance without running any constructor. Every field starts at its JVM default. - A missing **reference field** therefore stays `null`, even though Kotlin declares it `String`, not `String?`. - A missing **primitive** such as `Int` or `Boolean` silently becomes `0` or `false`, which is worse, because no exception ever fires. - If **every** constructor parameter has a default value, Kotlin generates a no-argument constructor. Gson calls it, so missing fields keep their declared defaults. - An **explicit `null`** in the JSON is still written into the field, default or not. ## Where the failure surfaces 1. The server stops sending `name` (a renamed key, a partial rollout, an R8-renamed field in a release build). 2. The response is a 200, so Retrofit runs the response converter. 3. Gson builds a `User` whose `name` field holds `null`. The converter returns it. 4. The suspend method returns normally. No `HttpException` (that is for non-2xx), no `IOException` (that is for transport failures). 5. Much later, `user.name.length` in a mapper, or a Kotlin function whose parameter is declared non-null, throws `NullPointerException`. The stack trace points at UI or domain code, and the crash report never mentions the network. That distance is the real cost: the error lands outside the `try`/`catch` around the call, so a screen crashes instead of showing an error state. ## Why Retrofit cannot catch it for you Retrofit sees a converter only as a function from `ResponseBody` to an object of the declared `Type`. It does one null check of its own: when a suspend method declares a non-null return type and the converted body as a whole is `null`, it throws a `KotlinNullPointerException` naming the service method. It never looks inside the object, so a `User` whose `name` is `null` passes. Kotlin's nullability for properties is enforced by code Kotlin compiles into constructors and function parameters; a converter that bypasses the constructor bypasses the check. The only place to enforce the contract is the converter itself, which is why the choice of factory matters more than any code around the call. ## How Kotlin-aware converters differ | Converter | Missing non-null field without a default | Where it fails | |---|---|---| | `GsonConverterFactory` | field holds `null` (or `0` for a primitive) | later, at first use | | kotlinx.serialization `asConverterFactory()` | the library throws a serialization exception naming the field | inside `convert()`, thrown from the call | | `MoshiConverterFactory` with a Kotlin-aware `Moshi` | Moshi throws a data exception for the required value | inside `convert()`, thrown from the call | Moshi honours Kotlin nullability only through its Kotlin support, generated adapters or its Kotlin reflection adapter, configured on the `Moshi` instance you pass to `MoshiConverterFactory.create(moshi)`; the Retrofit factory adds nothing Kotlin-specific. When a converter throws a runtime exception, Retrofit's call rethrows it unchanged (unless the underlying stream had already failed with an `IOException`, which is then reported instead), so the failure appears where the call is made. ## Fixing it in a Retrofit client - **Swap the converter**: register `Json.asConverterFactory("application/json".toMediaType())` in place of `GsonConverterFactory.create()`. The service interfaces do not change. The model classes gain the library's annotation, and endpoints can move one at a time behind a routing factory. - **Say what is optional**: make fields the API may omit nullable or give them defaults, so the model tells the truth about the contract. - **Treat a conversion failure as its own outcome**: once parsing fails inside the converter, the caller can tell "malformed response" from "no network". Classifying that outcome belongs to error handling. - **Test the contract**: run recorded JSON fixtures through the same `Retrofit` instance's converter, via `retrofit.responseBodyConverter<User>(User::class.java, emptyArray())`, so a release build cannot reach users with a model that silently accepts holes.
- Why might the same all-null model appear only in a release build of a Retrofit app using Gson?R8 can rename or remove model fields that only reflection reads. Gson then finds no field matching the JSON names, so every field keeps its default and the call still succeeds. The fix is keep rules for the model classes, or a converter whose adapters are generated at compile time, so field names are not looked up reflectively at runtime.
- How would you catch this class of bug before it reaches users?Write contract tests that feed recorded payloads, including ones with fields removed, through the app's real converter. Get it from the configured `Retrofit` instance with `responseBodyConverter`, or run a mock-server test, and assert that a missing required field fails at parse time. Under Gson that test exposes the silent null; after moving to a Kotlin-aware converter it should throw.
- Gson respects Kotlin non-null types and throws when a field is missing
- A missing field makes Retrofit report the call as an HttpException
- Gson always applies Kotlin default parameter values for missing fields
- Retrofit validates the parsed model against the declared Kotlin type
- A missing Int field arrives as null and crashes on use