With Retrofit, why must ScalarsConverterFactory be added before a JSON converter factory when one endpoint returns plain text?
answer
- first non-null wins
- some factories claim every type
- scalars returns null for models
- built-ins always sit in front
basics
~20 sRetrofit asks converter factories in the order they were added and uses the first non-null converter. JSON factories claim every type, so a String return reaches the JSON parser and plain text fails; scalars must come first to claim String.
solid answer
~40 sRetrofit keeps one list of converter factories: its built-in converters first, then yours in `addConverterFactory` order, then platform defaults. For each type it asks them in turn and takes the first converter that is not null. `ScalarsConverterFactory` answers only for `String` and the primitives and their boxes, returning null for anything else, so it is safe to put early. `GsonConverterFactory`, `MoshiConverterFactory` and kotlinx.serialization's `asConverterFactory()` never return null, and their docs say to add them last. With the JSON factory first, `suspend fun legacyStatus(): String` gets a JSON converter and the plain-text body fails to parse. With scalars first it is read as text, while `User` still falls through to JSON. Because the built-ins come first, `ResponseBody`, `RequestBody`, `Unit` and `Void` can never be overridden.
code
kotlin · 13 linesinterface LegacyApi {
@GET("status")
suspend fun legacyStatus(): String // text/plain body: OK
@GET("me")
suspend fun me(): User // application/json body
}
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(ScalarsConverterFactory.create()) // claims String only
.addConverterFactory(Json.asConverterFactory("application/json".toMediaType())) // claims the rest
.build()go deeper
Remember the rule: add ScalarsConverterFactory and any delegating body factory before the JSON factory, which goes last.
Explain the ordered list, first-non-null wins, which factories return null and which claim everything, and why the built-ins cannot be overridden.
Diagnose an order bug from its symptoms, such as a quoted string body or a delegating factory never called, and read the Tried and Skipped lists in the error.
Own the converter list as shared infrastructure: one builder, a documented order, and a routing factory rather than order tricks when two JSON libraries must coexist.
## How Retrofit picks a converter When `Retrofit.Builder.build()` runs, it assembles one ordered list of **converter factories**: 1. Retrofit's own built-in converters, always at index 0. 2. Every factory you passed to `addConverterFactory`, in the order you added them. 3. Platform defaults: on Android API 24 and above, a factory for Java's `Optional<T>`. When a service method is first parsed, Retrofit walks this list for the response type (and for each `@Body` type), calling `responseBodyConverter` or `requestBodyConverter` on each factory. The **first non-null converter wins** and the search stops. There is no notion of "most specific match", no look at the response's `Content-Type`, and no ambiguity check. Position decides. The lookup happens once per method, when it is first parsed, and the chosen converter is cached with the method. `build()` also copies the factories into an unmodifiable list, so editing the builder's list afterwards does not change an existing `Retrofit` instance. ## Which factories step aside | Factory | Claims | Returns null for | |---|---|---| | built-in converters | `ResponseBody`, `Unit`, `Void` responses; `RequestBody` bodies | everything else | | `ScalarsConverterFactory` | `String`, the eight primitives and their boxes, in both directions | every other type | | `GsonConverterFactory` | every type | nothing | | `MoshiConverterFactory` | every type | nothing | | kotlinx.serialization `asConverterFactory()` | every type with a serializer | nothing; it fails instead of stepping aside | | `OptionalConverterFactory` | `Optional<T>`, delegating `T` | everything else | The Gson, Moshi and kotlinx.serialization factories document this directly: because they assume they can handle all types, you must add them last so other converters get a chance to see their types. ## The legacy plain-text endpoint Picture a client being moved to kotlinx.serialization in which one legacy endpoint returns `OK` as `text/plain`, declared as `suspend fun legacyStatus(): String`. - **JSON factory first:** the JSON factory claims `String`, so Retrofit decodes the body as a JSON string literal. An unquoted `OK` is not valid JSON, and the call fails with the serialization library's parse exception. - **Scalars first:** `ScalarsConverterFactory` returns its string converter for `String` and reads the body as text. For `User`, scalars returns null and the JSON factory is consulted next. The request side has the same trap. A `@Body status: String` with scalars first goes out as `text/plain; charset=UTF-8` with the raw text. With a JSON factory first, it goes out as a JSON string, with quotes, and the JSON factory's content type. ## Symptoms of the wrong order - A `String` endpoint fails to parse while every model endpoint works. - A string `@Body` reaches the server wrapped in quotes. - A custom delegating factory (envelope unwrapping, a per-method router) is silently never called, because the JSON factory ahead of it claimed the type first. - `Optional<T>` responses fail to unwrap on API 24+, because the default `Optional` factory sits after yours and the JSON factory claimed `Optional` before it. ## Things order cannot change - **Built-ins always win.** They are inserted before your factories, so `ResponseBody`, `Unit`, `Void` and a `RequestBody` body can never be redirected to a custom converter. - **Two all-type factories cannot share a client by order alone.** Whichever is first claims every type. A migration that keeps both needs a delegating factory, added first, that routes each method to one or the other. - **String conversion is a different search.** `stringConverter` (for `@Query`, `@Path`, `@Header`) is also first-non-null, but the JSON factories do not implement it, so their position does not affect parameter rendering. ## A safe default order Most Android clients can follow one rule of thumb when adding factories: 1. Delegating factories that wrap or route, such as an envelope unwrapper or a per-method router during a migration. 2. Narrow factories that return null for most types: `ScalarsConverterFactory.create()`, and `OptionalConverterFactory.create()` if the interface returns `Optional`. 3. Exactly one all-type JSON factory, last. Writing the builder in one place (a single DI provider, for instance) keeps that order from being rearranged by a well-meaning edit in a feature module. ## Reading the error when it goes wrong When nothing matches, the exception's cause, "Could not locate ResponseBody converter for …", lists every factory it tried, in order. When a delegating factory calls `nextResponseBodyConverter`, the message also lists the factories it skipped. Reading that list is the quickest way to confirm the order the builder actually produced. `Retrofit.converterFactories()` returns the same list at runtime, built-ins included.
- Can two all-type JSON factories, say Gson and kotlinx.serialization, coexist in one Retrofit client during a migration?Not by order alone: whichever is added first claims every type and the second never runs. Coexistence needs a small delegating `Converter.Factory`, added first, that holds both factories and calls the chosen one's `responseBodyConverter` per method, for example by an opt-in method annotation, since Retrofit passes the method's annotations to the factory. Endpoints then move one at a time.
- Why might Optional<T> fail to unwrap when GsonConverterFactory is registered, and what changed in Retrofit 2.11.0?On API 24 and above Retrofit installs `OptionalConverterFactory` by default, but after your factories, and Gson claims every type, `Optional` included, first. Since 2.11.0 `OptionalConverterFactory` is public, so you can add `OptionalConverterFactory.create()` before the JSON factory; it then wraps whatever the JSON converter returns for the inner type.
A row of help desks where you are served by the first clerk who says "I can take that"; a generalist sitting at the first desk serves everyone, so the specialist must sit in front of the generalist.
- Retrofit picks the converter from the response Content-Type header
- Retrofit chooses the most specific factory regardless of order
- Registering two factories for the same type makes build() fail
- Scalars should go last because it is the fallback for simple types
- A custom converter can override how ResponseBody or Unit are handled
Assumes Retrofit 3.0.0; OptionalConverterFactory became public in 2.11.0 so it can be installed ahead of an all-type JSON factory.