skip to content

Converters

Converter factories that turn request and response bodies into Kotlin models and back, and a custom Converter.Factory. Asked as how JSON becomes a data class, and what breaks when a field is missing.

on this pageshow

explore

questions

6

In Retrofit 3, what does a converter factory do, and what happens if a service method returns a data class with none registered?

level: juniorimportance: must knowfreq 70%

answer

  1. format-agnostic core
  2. bytes to model and back
  3. built-ins: OkHttp body types, Unit, Void
  4. fails when the method is first parsed

basics

~20 s

A Retrofit converter factory turns a successful response body into the declared type and a @Body value into a request body. With none added, only ResponseBody, RequestBody, Unit and Void work; a data class fails with "Unable to create converter".

solid answer

~40 s

Retrofit's core is format-agnostic: out of the box it converts only OkHttp's `ResponseBody` and `RequestBody`, plus `Unit` and `Void` for a body you discard. A `Converter.Factory` added with `addConverterFactory` supplies everything else: `responseBodyConverter` turns a 2xx body into the declared type, `requestBodyConverter` serializes `@Body` values, and `stringConverter` renders `@Path`, `@Query` and `@Header` values. If a method returns a data class and no factory claims it, `create()` still succeeds, but the first call to that method throws an `IllegalArgumentException`, "Unable to create converter for …", whose cause lists every factory it tried. `validateEagerly(true)` moves that failure into `create()`. In Retrofit 3 the kotlinx.serialization factory comes from `com.squareup.retrofit2:converter-kotlinx-serialization` (in the Retrofit repo since 2.10.0) and is built with `Json.asConverterFactory(contentType)`.

code

kotlin · 24 lines
kotlin
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
import retrofit2.Retrofit
import retrofit2.converter.kotlinx.serialization.asConverterFactory
import retrofit2.create
import retrofit2.http.GET
import retrofit2.http.Path

@Serializable
data class Repo(val id: Long, val name: String)

interface RepoService {
  @GET("users/{user}/repos")
  suspend fun repos(@Path("user") user: String): List<Repo>
}

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

val service: RepoService = retrofit.create()

go deeper

for a junior

Recall that Retrofit needs a converter factory to turn JSON into a data class, and that you add one with addConverterFactory on the builder.

for a middle

Explain the three factory methods, what works without any converter, and why the missing-converter error appears on the first call rather than at build().

for a senior

Show you would catch converter mistakes before users do, with validateEagerly in debug or a test, and know which thread does request and response conversion.

for a principal

Treat the converter as a client-wide contract: one factory list built once and shared, chosen deliberately, and covered by tests that fail the build rather than a screen.

## What a converter is Retrofit turns a Kotlin interface into HTTP calls, but its core deliberately knows nothing about JSON, XML or protocol buffers. That knowledge lives in two small types: - **`Converter<F, T>`** has one method, `convert(value: F): T`. It turns one representation into another, for example a `ResponseBody` into a `User`. - **`Converter.Factory`** is an abstract class whose methods receive a `java.lang.reflect.Type` plus the relevant annotations and return a converter for that type, or `null` when the factory cannot handle it. You register factories with `Retrofit.Builder.addConverterFactory(...)`. Retrofit asks them in order and uses the first converter that is not `null`, which is why the order of registration matters (a separate question covers that in depth). ## The three directions A factory can override any of three methods; each one defaults to returning `null`. | Factory method | Converts | Used for | |---|---|---| | `responseBodyConverter` | `ResponseBody` to the declared type | the body of a successful response, such as `List<Repo>` from `suspend fun repos(): List<Repo>` | | `requestBodyConverter` | a value to `RequestBody` | `@Body`, `@Part` and `@PartMap` arguments | | `stringConverter` | a value to `String` | `@Path`, `@Query`, `@QueryMap`, `@Header`, `@HeaderMap`, `@Field` and `@FieldMap` arguments | The JSON factories Retrofit ships (`GsonConverterFactory`, `MoshiConverterFactory`, kotlinx.serialization's `asConverterFactory()`) override only the two body methods. ## What works with no converter at all Retrofit always installs its own built-in converters ahead of yours, so a bare `Retrofit.Builder` still handles: - **`ResponseBody`** as a return type: the body is buffered fully, or handed over unbuffered when the method carries `@Streaming`. - **`RequestBody`** as a `@Body` argument, passed through unchanged. - **`Unit`** (since Retrofit 2.5.0, broadened in 2.10.0) and **`Void`**: the body is closed and discarded without being parsed. - **Strings for parameters**: when no factory offers a `stringConverter`, Retrofit falls back to calling `toString()`. - On Android API 24 and above, a default factory for Java's `Optional<T>`, which only wraps another converter for `T` and so still needs one. A response converter also runs only on bodies that matter. A non-2xx body is buffered and exposed as an error body without conversion, and a 204 or 205 response yields a null body without calling the converter. ## Registering a converter in Retrofit 3 Retrofit 3.0.0 changed one thing: it moved to OkHttp 4.12 (from 3.14), which brings a transitive Kotlin dependency and the `toMediaType()` extension. Converters work as they did in 2.12. The kotlinx.serialization converter was imported into the Retrofit repository in 2.10.0 under `com.squareup.retrofit2:converter-kotlinx-serialization`; you call `asConverterFactory` on a configured `Json` and pass the media type that request bodies will declare as `Content-Type`. The converter artifact depends only on Retrofit and the serialization core, so the app still adds the JSON format artifact and the serialization plugin itself. ```kotlin val retrofit = Retrofit.Builder() .baseUrl("https://api.example.com/") .addConverterFactory(Json.asConverterFactory("application/json".toMediaType())) .build() ``` ## When a missing converter is noticed The failure is lazy, which surprises people who expect `build()` to validate everything: 1. `Retrofit.Builder.build()` assembles the factory lists and succeeds. 2. `create()` returns a proxy for the interface and also succeeds. 3. On the **first call** to a method, Retrofit parses that method: its annotations, its call adapter and its response converter. 4. If every factory returns `null` for the response type, Retrofit throws an `IllegalArgumentException` reading "Unable to create converter for …" followed by "for method RepoService.repos". Its cause, "Could not locate ResponseBody converter for …", lists every factory under "Tried:", which tells you at a glance that no JSON factory was registered. 5. With `Retrofit.Builder.validateEagerly(true)`, steps 3 and 4 run for every declared method inside `create()`, so the mistake fails at startup or in a unit test instead of on a user's tap. A `@Body` argument with no matching factory fails at the same moment, with "Unable to create @Body converter for …" caused by "Could not locate RequestBody converter for …". ## Where conversion runs A suspend method is driven by `Call.enqueue`, so the response converter runs on one of OkHttp's background threads before the coroutine resumes. Request bodies are converted when the HTTP request is built, which for `enqueue` means on the thread that starts the call; Retrofit 2.12.0 added `withStreaming()` to the Gson, Jackson, Moshi, Protobuf and Wire factories to defer that work until OkHttp writes the body. ## What interviewers listen for - That Retrofit itself parses nothing; the factory does. - The three factory methods and which annotations each serves. - That the error appears on first use, not at `build()`, and how `validateEagerly(true)` changes that. - In Retrofit 3, the right artifact for kotlinx.serialization and the media type it needs.

  • On which thread does Retrofit run the response converter for a suspend service method?
    A suspend method is driven by `Call.enqueue`, so parsing happens inside OkHttp's response callback on one of its background threads, before the coroutine resumes; it never parses on the main thread. Request bodies differ: by default they are converted when the request is built, on the thread that starts the call. Since 2.12.0, `withStreaming()` on the Gson, Moshi, Jackson, Protobuf and Wire factories defers that to OkHttp's write.
  • What does validateEagerly(true) cost, and where would you enable it?
    It makes `create()` parse every declared method up front (annotations, call adapter and converters) instead of on first use, so a missing converter or a bad annotation fails immediately. The cost is that reflective work running on the thread that calls `create()`, which adds startup time for a large interface. Many teams enable it in debug builds, or in a unit test that creates every service.

  • Retrofit parses JSON itself and the converter is only an optimisation
  • A missing converter makes Retrofit.Builder.build() throw immediately
  • Without a converter, Retrofit returns the body as a String
  • The converter also parses 4xx and 5xx bodies into the declared type
  • kotlinx.serialization needs a third-party converter artifact in Retrofit 3

Assumes Retrofit 3.0.0; Unit responses arrived in 2.5.0 and were broadened in 2.10.0, the in-repo kotlinx.serialization converter arrived in 2.10.0, and 3.0.0 changed only the OkHttp dependency.

open as a page

With Retrofit, why must ScalarsConverterFactory be added before a JSON converter factory when one endpoint returns plain text?

level: middleimportance: must knowfreq 62%

basics

~20 s

Retrofit 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.

open as a page

In Retrofit, why does a Kotlin enum passed as @Query send its constant name, and how does a stringConverter change that?

level: middleimportance: should knowfreq 30%

basics

~20 s

Retrofit renders @Query, @Path, @Header and @Field values through stringConverter. The Gson, Moshi and kotlinx factories don't implement it, so Retrofit falls back to toString() and sends ACTIVE. A custom Converter.Factory overriding stringConverter sends the API's spelling instead.

open as a page

How do you write a Retrofit Converter.Factory that unwraps a {"data": ...} API envelope by delegating to the JSON converter?

level: seniorimportance: should knowfreq 38%

basics

~10 s

Subclass Converter.Factory; in responseBodyConverter build the type Envelope<T>, get its converter from retrofit.nextResponseBodyConverter(this, ...), and return a converter that delegates and takes data. Register it before the JSON factory, which otherwise claims T first.

open as a page

With Retrofit and GsonConverterFactory, why can a missing JSON field leave a non-null Kotlin property null, and where does it fail?

level: seniorimportance: should knowfreq 52%

basics

~20 s

Gson'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.

open as a page

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%

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.

open as a page