skip to content

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%

answer

  1. non-body parameters become text
  2. JSON factories skip one method
  3. the toString() fallback
  4. return null for types you don't own

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.

solid answer

~40 s

Non-body parameters (`@Path`, `@Query`, `@QueryMap`, `@Header`, `@Field`) become strings through `Converter.Factory.stringConverter`. Retrofit asks every registered factory, and if none returns a converter it uses a built-in one that calls `toString()`. The JSON factories (`GsonConverterFactory`, `MoshiConverterFactory`, `asConverterFactory()`) override only the body methods, so an enum's `@SerializedName` or `@SerialName` shapes JSON bodies but not the query string: `?status=ACTIVE` goes out while the API expects `active`. The fix is a small factory whose `stringConverter` recognises your type and returns a converter (for example, enums implementing an `ApiValue` interface render `apiValue`) and returns null for every other type. Because the JSON factories never answer this method, the custom factory works wherever it sits in the list.

code

kotlin · 34 lines
kotlin
import java.lang.reflect.Type
import retrofit2.Converter
import retrofit2.Retrofit
import retrofit2.http.GET
import retrofit2.http.Query

interface ApiValue {
  val apiValue: String
}

enum class Status(override val apiValue: String) : ApiValue {
  ACTIVE("active"),
  ARCHIVED("archived"),
}

class ApiValueConverterFactory : Converter.Factory() {
  override fun stringConverter(
    type: Type,
    annotations: Array<out Annotation>,
    retrofit: Retrofit,
  ): Converter<*, String>? {
    val raw = type as? Class<*> ?: return null
    if (!ApiValue::class.java.isAssignableFrom(raw)) return null
    return Converter<ApiValue, String> { it.apiValue }
  }
}

interface ArticleApi {
  // Without the factory: ?status=ACTIVE. With it: ?status=active
  @GET("articles")
  suspend fun articles(@Query("status") status: Status): List<Article>
}

data class Article(val id: Long, val title: String)

go deeper

for a junior

Recall that @Query and @Path values become text, and an enum is sent by its constant name unless you change that.

for a middle

Explain stringConverter, the toString() fallback, and why JSON naming annotations affect bodies but never query parameters.

for a senior

Write the factory, return null for types you don't own, and know how null values, null conversions and collections are handled.

for a principal

Decide where wire formats for parameters live and enforce one factory for them, so dates and enums cannot drift endpoint by endpoint.

## Where stringConverter is used Retrofit's `Converter.Factory` has three methods. Two handle bodies; the third, **`stringConverter`**, turns a parameter value into the text that goes into the URL, a header or a form field. Retrofit's own documentation lists its users: - `@Path` and `@Query` / `@QueryMap` values in the URL - `@Header` / `@HeaderMap` values - `@Field` / `@FieldMap` values in a form-encoded body A `@Body` value never goes through it; that is `requestBodyConverter`'s job. Besides the parameter's `Type`, the factory receives that parameter's annotations, so an app-defined annotation on one parameter can select a different format for it. ## The toString() fallback When Retrofit parses a method, it looks up a string converter for each such parameter type: 1. It asks every factory in the list, built-ins first, for `stringConverter(type, annotations, retrofit)`. 2. The first non-null converter is used for every call to that method. 3. If **no** factory answers, Retrofit uses a built-in converter that simply calls `toString()`. For a Kotlin enum, `toString()` returns the constant's name, so `Status.ACTIVE` becomes `status=ACTIVE`. For a date class or a value wrapper it is whatever that class prints, which is rarely the API's format. ## Why JSON annotations don't help The first-party JSON factories implement `responseBodyConverter` and `requestBodyConverter` only. Their annotations therefore change JSON bodies and nothing else: | What you annotate | JSON `@Body` and responses | `@Query`, `@Path`, `@Header` values | |---|---|---| | Gson's `@SerializedName("active")` on an enum constant | `"active"` | `ACTIVE` (via `toString()`) | | kotlinx.serialization's `@SerialName("active")` | `"active"` | `ACTIVE` (via `toString()`) | | a custom `stringConverter` | unchanged | `active` | This mismatch is a classic: the same enum serializes correctly in a request body and incorrectly in a filter parameter, and the server either rejects the request or, worse, ignores an unknown filter value and returns unfiltered results. ## Writing the factory The factory only needs `stringConverter`. Recognise your type, return a converter, and return `null` for everything else so other types keep their normal handling: ```kotlin override fun stringConverter( type: Type, annotations: Array<out Annotation>, retrofit: Retrofit, ): Converter<*, String>? { val raw = type as? Class<*> ?: return null if (!ApiValue::class.java.isAssignableFrom(raw)) return null return Converter<ApiValue, String> { it.apiValue } } ``` Register it with `addConverterFactory`. Because the JSON factories return `null` from `stringConverter`, its position relative to them does not matter **for parameters**. Position matters again only if the same factory also overrides a body method. ## Nulls and collections - A `null` argument for `@Query`, `@Header` or `@Field` is skipped: the parameter is simply left out. - A string converter that returns `null` for a `@Query`, `@Header` or `@Field` value also makes Retrofit skip it (for `@Query` and `@Field` since 2.3.0), a handy way to omit a "no filter" sentinel. - A `null` `@Path` argument is rejected with "Path parameter … value must not be null", and a `@QueryMap` value that is `null`, or converts to `null`, is rejected too. - For an `Iterable` or array `@Query`, Retrofit looks up the converter for the **element** type and adds one parameter per element: `status=active&status=archived`. ## Common mistakes - Assuming `@SerializedName` or `@SerialName` reaches the URL; they apply only where the JSON converter runs. - Returning a converter for every type. The factory then also renders `String`, `Int` and every other parameter, so return `null` for anything you did not mean to handle. - Formatting values by hand at each call site with a `String` parameter, which spreads the wire format across the codebase and loses the type. - Testing only request bodies. A unit test that inspects the built request URL (for example through a mock server) is what catches a wrong query spelling. ## When to reach for it - Enums whose wire spelling differs from the Kotlin constant names. - Date and time types that must use one format across every endpoint. - Value classes or IDs that should print their raw value, not a debug `toString()`. Keeping that mapping in a factory means one place defines the wire format for parameters, consistently across `@Path`, `@Query`, `@Header` and `@Field`.

  • How does Retrofit render a List<Status> passed as a single @Query parameter?
    Retrofit asks for a string converter for the element type, `Status`, not for `List`, and adds one query parameter per element, so with the custom factory you get `status=active&status=archived`. Null elements are skipped. If the API expects one comma-separated value instead, join the list yourself into a `String` parameter, or pass a wrapper type that your string converter renders.
  • Why not simply override toString() on the enum instead of writing a factory?
    It works, since the fallback converter calls `toString()`, but it ties every log line, debug print and string template to the wire format. It also does nothing for types you don't own, such as a date class. A string converter keeps the wire format inside the network layer and applies the same rule to `@Path`, `@Query`, `@Header` and `@Field`.

  • @SerializedName on an enum constant also changes its @Query value
  • Retrofit sends @Query enums through the JSON converter
  • stringConverter is used to serialize @Body values
  • A custom stringConverter factory must be added before the JSON factory
  • Retrofit sends an enum's ordinal when no converter matches