skip to content

As Android lead, which JSON converter should a Retrofit codebase standardise on, and how do you move 60 Gson endpoints without a big-bang switch?

level: principalimportance: should knowfreq 28%

answer

  1. one converter is a codebase default
  2. the JSON factories never step aside
  3. route by an opt-in method annotation
  4. contract tests on recorded payloads
  5. delete the router when the last endpoint moves

basics

~10 s

Standardise on one JSON converter that respects Kotlin nullability, usually kotlinx.serialization, and migrate endpoint by endpoint: a routing factory sends opted-in methods to the new converter, and Gson stays last as the default.

solid answer

~40 s

There is no universal winner, so I decide from the codebase. A Kotlin-first or Multiplatform app standardises on kotlinx.serialization's `asConverterFactory()`. A team already on a Kotlin-aware Moshi setup can stay there. Gson's reflective converter is the one I would retire, because it can leave non-null properties null. The move is per endpoint. The JSON factories never return null, so they cannot be stacked. I add a routing `Converter.Factory` that returns the new converter for methods carrying an opt-in annotation and `null` for the rest, with Gson registered last. Each endpoint moves with a contract test that decodes recorded payloads through both converters, and conversion failures are watched after each release. When the last endpoint moves, the router, the annotation and Gson are deleted together.

code

kotlin · 34 lines
kotlin
import java.lang.reflect.Type
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.kotlinx.serialization.asConverterFactory

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class KotlinxJson

class MigrationConverterFactory(private val next: Converter.Factory) : Converter.Factory() {
    override fun responseBodyConverter(
        type: Type, annotations: Array<out Annotation>, retrofit: Retrofit,
    ): Converter<ResponseBody, *>? =
        if (annotations.any { it is KotlinxJson }) next.responseBodyConverter(type, annotations, retrofit) else null

    override fun requestBodyConverter(
        type: Type, parameterAnnotations: Array<out Annotation>,
        methodAnnotations: Array<out Annotation>, retrofit: Retrofit,
    ): Converter<*, RequestBody>? =
        if (methodAnnotations.any { it is KotlinxJson }) {
            next.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit)
        } else null
}

val retrofit: Retrofit = Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(MigrationConverterFactory(Json.asConverterFactory("application/json".toMediaType())))
    .addConverterFactory(GsonConverterFactory.create())
    .build()

go deeper

for a junior

Know that Retrofit needs a converter factory to read JSON into Kotlin classes, and that an app normally registers one JSON library for all its endpoints.

for a middle

Explain factory order: Retrofit asks factories in turn and takes the first non-null converter, which is why an all-type JSON factory goes last.

for a senior

Show how a routing Converter.Factory delegates by method annotation and returns null otherwise, and how contract tests compare both converters on recorded payloads.

for a principal

Own the choice and the rollout: which converter the codebase standardises on and why, the order endpoints move in, what gates each step, and when the old converter and the router are deleted.

## The decision A Retrofit app registers its JSON converter once, in the `Retrofit.Builder`, and every endpoint inherits it. That makes the converter a **codebase-wide default** that a lead owns: which library turns JSON into Kotlin models, and, when the current one is wrong for the code, how to change it without a release that flips sixty endpoints at once. There is no single right converter. The choice follows the codebase, and the migration is where most of the risk lives. ## Choosing the converter to standardise on | Factory | How it reads a Kotlin class | A missing non-null field | What the team takes on | |---|---|---|---| | `GsonConverterFactory` | reflection, unaware of Kotlin nullability | can leave the property null; the crash comes later, far from the call | nothing new, which is why many apps still carry it | | `MoshiConverterFactory` | Kotlin-aware when the `Moshi` instance has Kotlin support | fails inside `convert()` | code generation or a reflection adapter, configured on the `Moshi` instance | | kotlinx.serialization `asConverterFactory()` | serializers generated by the compiler plugin | fails inside `convert()` | the plugin and a `@Serializable` annotation on every model | The usual reasoning: - A **Kotlin-first app, or one with Multiplatform modules**, standardises on kotlinx.serialization, because the models can then be shared with non-Android code. - A team **already on a Kotlin-aware Moshi setup** gains little by moving and can stay there. - **Gson is the converter most often retired**. Its silent nulls in non-null properties surface as crashes in UI code, where nobody looks for a parsing bug. The serialization libraries' own configuration and annotations are outside this decision. What matters here is how the choice plays out in Retrofit's converter layer. ## Why two JSON factories cannot simply be stacked Retrofit asks its built-in converters first, then your factories in `addConverterFactory` order, and takes the first converter that is not null. The JSON factories never step aside. Gson and Moshi return a converter for any type. kotlinx.serialization's factory looks up a serializer for the type and throws when there is none, and Retrofit reports that as `Unable to create converter for ...` instead of moving to the next factory. Registering the new factory first therefore breaks every endpoint that has not moved yet. ## A routing factory makes the move incremental 1. Declare an opt-in annotation, such as `@KotlinxJson`, with runtime retention (the Kotlin default). 2. Write a small `Converter.Factory` that returns the new converter when a method carries the annotation and `null` otherwise. Retrofit passes the service method's annotations to `responseBodyConverter`, and both the parameter and method annotations to `requestBodyConverter`, so one method annotation routes both directions. 3. Register the router ahead of the old JSON factory, and keep that factory **last** as the default for everything not yet moved. A `ScalarsConverterFactory` still goes before both. Retrofit's own samples show this pattern as an annotation-routed converter factory. The alternative is **two `Retrofit` instances sharing one `OkHttpClient`**, one per converter. That needs no custom code, but it moves a whole service interface at a time, and DI has to give each service the right instance. ## Rolling it out endpoint by endpoint - **Move a method's request and response together**, so one endpoint never mixes the two libraries. - **Write a contract test before flipping each endpoint.** Decode recorded production payloads through both converters with `MockWebServer` and compare the models. Gson and kotlinx.serialization disagree on missing fields, unknown keys and nulls, and that is where regressions hide. - **Ship a few endpoints per release**, starting with low-traffic reads. A conversion failure then points to one change. - **Watch conversion failures as contract bugs.** They arrive as exceptions from `convert()`, and the data layer should report them to crash reporting, never as an offline message. ## Finishing, and when not to start The migration is done when the last endpoint carries the annotation. Then delete the router, the annotation and the Gson dependency in one change, and register the new factory directly. An annotation left behind "as documentation" is a rudiment that the next developer copies. Not every app should start. A small Gson codebase with a stable backend and no history of null crashes may not repay the work, and an app about to be rewritten should move with the rewrite. Write the decision down either way: a new endpoint must use the agreed converter, so the old one stops growing.

  • Why not register kotlinx.serialization's factory before Gson and let it take only the types it knows?
    Because it never steps aside. It looks up a serializer for the requested type and throws when none exists, and Retrofit reports that as `Unable to create converter for ...` rather than asking the next factory. Every endpoint that has not moved would fail on first use, or at `create()` with `validateEagerly(true)`. Only a factory that returns `null` hands a type on.
  • When would you choose two Retrofit instances over a routing factory?
    When service interfaces already match areas of the app, and moving a whole interface at once is acceptable. Two builders sharing one `OkHttpClient` need no custom converter code and keep one connection pool. The cost is coarser steps: an interface that mixes moved and unmoved endpoints must be split first, and DI must hand each service the right instance.
  • How do you decide an endpoint is safe to move?
    A contract test decodes recorded production payloads through both converters and compares the models, including payloads with missing fields, extra keys and nulls. After the release, conversion failures from that method stay at zero in crash reporting. Only then does the next batch move.

  • Adding the new JSON factory first lets it handle only the types it supports.
  • A converter migration has to switch every endpoint in one release.
  • Retrofit picks the converter from the response's Content-Type header.
  • Gson and kotlinx.serialization decode the same payload identically, so no tests are needed.
  • The routing annotation can stay after the migration as documentation.

Assumes Retrofit 3.0.0. The kotlinx.serialization converter has been published as com.squareup.retrofit2:converter-kotlinx-serialization since 2.10.0; before that it was a separate project with its own coordinates.