Retrofit Converters: Speaking Your API's Language
A Retrofit Converter is a translator that turns raw network data into your app's data classes (e.g., JSON to Kotlin objects). You add a converter factory, like for Moshi or Gson, when building your Retrofit instance. The footgun: converter order matters.
WHY IT EXISTS Retrofit's core job is making HTTP requests, not parsing data. Out of the box, it can only give you a raw ResponseBody object. This is inconvenient; you almost always want structured data like a User object, not a blob of JSON bytes you have to parse manually. Converters bridge this gap, automating the serialization and deserialization process.
THE MENTAL MODEL Think of a Retrofit Converter as a specialized translator at a border crossing. The raw HTTP response (the traveler) arrives speaking a foreign language (JSON, XML, Protobuf). The converter's job is to translate that language into one your application understands (your Kotlin data classes) and vice-versa for outgoing requests. You install the translator for the specific language your API speaks.
HOW IT WORKS When you build your Retrofit instance, you call addConverterFactory(), passing in a factory like MoshiConverterFactory.create(). When an API call is made, Retrofit looks at your service interface's return type (e.g., User). It then iterates through its list of registered converter factories, asking each one, "Can you convert this HTTP response into a User object?". The first factory that says "yes" gets the job. The same logic applies in reverse for request bodies annotated with @Body.
WHEN TO USE IT Use a converter whenever your API communicates with a structured data format like JSON, XML, or Protobuf. This is standard practice for virtually all Retrofit setups. Common choices for Android include converter-kotlinx-serialization for pure Kotlin projects, converter-moshi, or converter-gson. You might also use converter-scalars to handle plain strings or primitives.
WHEN NOT TO USE IT You might omit converters if you only need the raw ResponseBody to perform custom, low-level operations, like streaming a large file directly to disk. For 99% of typical application development involving REST APIs, you will use a converter.
ONE CANONICAL EXAMPLE To make Retrofit understand JSON using the Moshi library, first add the dependency com.squareup.retrofit2:converter-moshi. Then, when building your Retrofit client, add its factory: Retrofit.Builder().baseUrl("https://api.example.com/").addConverterFactory(MoshiConverterFactory.create()).build(). Now, a service method defined as suspend fun getUser(): User will automatically parse the JSON response into a User data class instance.
Read the original → square.github.io
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.