skip to content

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%

answer

  1. wrap the type, then unwrap the value
  2. method annotations reach the factory
  3. skip past yourself
  4. register before the JSON factory

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.

solid answer

~40 s

In `responseBodyConverter`, first decide whether this method is enveloped (an opt-in method annotation works, because Retrofit passes the method's annotations to the factory) and return null otherwise. For an enveloped method, build a `ParameterizedType` for `Envelope<T>` around the requested type and call `retrofit.nextResponseBodyConverter(this, envelopeType, annotations)`; the search starts after your factory and lands on the JSON converter. Return a converter that delegates and returns `.data`. Order is the whole trick: add the envelope factory before `GsonConverterFactory` or `asConverterFactory()`, because those claim every type and would parse the bare `T`. Two edges: if `data` is null and the suspend method's return type is non-null, Retrofit throws a `KotlinNullPointerException`; and response converters run only on successful bodies, so error bodies never pass through it.

code

kotlin · 36 lines
kotlin
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import kotlinx.serialization.Serializable
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit

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

@Serializable
data class Envelope<T>(val data: T)

class EnvelopeConverterFactory : Converter.Factory() {
  override fun responseBodyConverter(
    type: Type,
    annotations: Array<out Annotation>,
    retrofit: Retrofit,
  ): Converter<ResponseBody, *>? {
    if (annotations.none { it is Enveloped }) return null
    val delegate: Converter<ResponseBody, Envelope<Any?>> =
      retrofit.nextResponseBodyConverter(this, EnvelopeOf(type), annotations)
    return Converter<ResponseBody, Any?> { body -> delegate.convert(body)?.data }
  }

  private class EnvelopeOf(private val inner: Type) : ParameterizedType {
    override fun getRawType(): Type = Envelope::class.java
    override fun getActualTypeArguments(): Array<Type> = arrayOf(inner)
    override fun getOwnerType(): Type? = null
  }
}

// Retrofit.Builder()
//   .addConverterFactory(EnvelopeConverterFactory())       // first
//   .addConverterFactory(json.asConverterFactory(mediaType)) // last

go deeper

for a junior

Know that a converter factory can unwrap a wrapper object so service methods return the model directly.

for a middle

Explain how a factory delegates to the next converter and why it must be registered before the JSON factory.

for a senior

Build it end to end: opt-in annotation, a ParameterizedType, nextResponseBodyConverter with this, plus the null-payload and error-body edges.

for a principal

Decide whether envelope handling belongs in the converter layer or in a repository mapper, given how errors, metadata and paging fields must reach callers.

## The problem Many APIs wrap every payload: `{"data": {"id": 7, "name": "Ada"}, "meta": {...}}`. Without help, every service method returns `Envelope<User>` and every caller writes `.data`. A **delegating converter factory** moves that unwrapping into Retrofit's converter layer, so the interface can declare `suspend fun me(): User` while the JSON library still does all the parsing. ## How delegation works in Retrofit Retrofit's converter lookup is an ordered list, and it exposes the list to factories: - Every factory method receives the `Retrofit` instance as a parameter. - `retrofit.responseBodyConverter(type, annotations)` searches the **whole** list from the start. - `retrofit.nextResponseBodyConverter(skipPast, type, annotations)` starts **after** `skipPast`, so a factory can ask "who else handles this?" without finding itself. - If nothing matches, the error message lists the factories under "Skipped:" and "Tried:", which shows the order at a glance. Calling `responseBodyConverter` from inside your own factory would be a bug: the search would reach your factory again, which would wrap the type again, recursing until the stack overflows. ## Building the factory 1. **Opt in per method.** Declare an annotation with runtime retention and function target, say `@Enveloped`. Retrofit passes a method's annotations to `responseBodyConverter`, so the factory can check for it. Return `null` when it is absent; other methods are untouched. 2. **Build the wrapped type.** Implement `java.lang.reflect.ParameterizedType` with raw type `Envelope::class.java` and one argument, the requested `type`. Gson, Moshi and kotlinx.serialization all resolve a generic class from such a type. 3. **Delegate.** Call `retrofit.nextResponseBodyConverter<Envelope<Any?>>(this, envelopeType, annotations)`. 4. **Unwrap.** Return `Converter<ResponseBody, Any?> { body -> delegate.convert(body)?.data }`. The converter is created once, when the method is first parsed, and cached with it, so the per-call overhead is one extra function call. ## Registration order | Order in the builder | Result for an `@Enveloped` method returning `User` | |---|---| | envelope factory, then JSON factory | envelope parsed by JSON, `data` returned | | JSON factory, then envelope factory | JSON factory claims `User` and decodes the envelope as a `User`; the envelope factory is never asked | With the wrong order the failure depends on the library: kotlinx.serialization typically throws on the unexpected or missing keys, while Gson may quietly return a `User` full of nulls. ## Edges worth knowing - **A null payload.** If `data` is `null` on a 200 and the method is `suspend fun me(): User`, Retrofit throws `KotlinNullPointerException` ("Response from … was null but response body type was declared as non-null"). Declaring `User?` returns `null` instead. - **Built-in types never reach you.** `Unit`, `Void` and `ResponseBody` are claimed by Retrofit's built-in converters before any added factory, so an annotated method with those return types is not unwrapped. - **Error bodies are separate.** Retrofit runs the response converter only for 2xx bodies (not 204 or 205). Turning an error body into a type is handled where errors are handled. - **Requests can be wrapped too.** Override `requestBodyConverter`, check the parameter or method annotations, and call `retrofit.nextRequestBodyConverter(this, envelopeType, parameterAnnotations, methodAnnotations)` to wrap the outgoing value. ## When not to unwrap - **The envelope carries data callers need.** Paging cursors, server timestamps or warnings in `meta` disappear once the converter returns only `data`; a typed `Envelope<T>` return is then the honest choice. - **The API reports failures inside a 200.** If the envelope holds a success flag or an error object, the converter must check it and throw, and that throw then has to be classified alongside network and HTTP failures. - **Only a few endpoints are wrapped.** The opt-in annotation keeps the factory harmless elsewhere, but a reader of the interface still has to know it exists; name the annotation plainly and keep the factory next to the builder. ## Testing it Because the factory is plain code, test it through the real `Retrofit` instance. Fetch the converter for `User` with the annotation present, feed it a recorded envelope, and assert on the unwrapped value and on the null-payload case. That keeps the order and the delegation under test, not only the unwrapping lambda.

  • How would the same Retrofit factory wrap outgoing @Body values in an envelope?
    Override `requestBodyConverter`, check the method or parameter annotations, and get the JSON converter for `Envelope<T>` with `retrofit.nextRequestBodyConverter(this, envelopeType, parameterAnnotations, methodAnnotations)`. Return a converter that builds `Envelope(value)` and passes it to the delegate. The same ordering rule applies: the factory must sit before the JSON factory.
  • Why does an @Enveloped Retrofit method that returns Unit or ResponseBody never reach the envelope factory?
    Retrofit inserts its built-in converters ahead of every added factory, and they claim `Unit`, `Void` and `ResponseBody` responses. The lookup stops there, so a custom factory can neither unwrap nor override those types. That is usually what you want: `Unit` discards the body and `ResponseBody` hands you the raw bytes.

  • Calling retrofit.responseBodyConverter inside the factory finds the next converter
  • Retrofit runs the envelope factory first because it is more specific
  • The envelope factory also unwraps error bodies automatically
  • A null data field makes a suspend method return null for a non-null type
  • Each converter factory must parse the JSON itself rather than delegating