Retrofit 2 — Adding & Customizing the Gson Converter

In our last Retrofit post we've given you an introduction to converters. In this blog post, we want to dive deeper into the most common format: JSON. After demonstrating the integration of the Gson converter, we'll also show you how to customize Gson's mapping rules.

If you prefer to catch up with other Retrofit topics first, give our outline a look:


Retrofit Series Overview

  1. Getting Started and Creating an Android Client
  2. Retrofit 2 — Basics of API Description
  3. Retrofit 2 — Creating a Sustainable Android Client
  4. Synchronous and Asynchronous Requests
  5. Send Objects in Request Body
  6. Add Custom Request Header
  7. Retrofit 2 — Manage Request Headers in OkHttp Interceptor
  8. Retrofit 2 — Dynamic Request Headers with @HeaderMap
  9. Multiple Query Parameters of Same Name
  10. Optional Query Parameters
  11. Using the Log Level to Debug Requests
  12. Retrofit 2 — Log Requests and Responses
  13. Retrofit 2 — Enable Logging for Development Builds Only
  14. How to Upload Files to Server
  15. Retrofit 2 — How to Upload Files to Server
  16. Retrofit 2 — How to Upload Multiple Files to Server
  17. Retrofit 2 — Passing Multiple Parts Along a File with @PartMap
  18. Basic Authentication on Android
  19. Token Authentication on Android
  20. OAuth on Android
  21. Retrofit 2 — Hawk Authentication on Android
  22. How to Refresh an Access Token
  23. Retrofit 2 — Upgrade Guide from 1.9
  24. Retrofit 2 — Simple Error Handling
  25. How to use OkHttp 3 with Retrofit 1
  26. Send Data Form-Urlencoded
  27. Send Data Form-Urlencoded Using FieldMap
  28. Retrofit 2 — How to Add Query Parameters to Every Request
  29. Retrofit 2 — Add Multiple Query Parameter With QueryMap
  30. Retrofit 2 — How to Use Dynamic Urls for Requests
  31. Retrofit 2 — URL Handling, Resolution and Parsing
  32. Retrofit 2 — Constant, Default and Logic Values for POST and PUT Requests
  33. Retrofit 2 — How to Download Files from Server
  34. Retrofit 2 — Cancel Requests
  35. Retrofit 2 — Reuse and Analyze Requests
  36. Retrofit 2 — How to Change API Base Url at Runtime
  37. Optional Path Parameters
  38. Retrofit 2 — How to Send Plain Text Request Body
  39. Retrofit 2 — Pagination Using Query Parameter
  40. Retrofit 2 — Pagination Using Link Header and Dynamic Urls (Like GitHub)
  41. Retrofit 2 — Pagination Using Range Header Fields (Like Heroku)
  42. How to Integrate XML Converter
  43. Define a Custom Response Converter
  44. Retrofit 2 — Introduction to (Multiple) Converters
  45. Retrofit 2 — Adding & Customizing the Gson Converter
  46. Retrofit 2 — Implementing Custom Converters
  47. Retrofit 2 — Basics of Mocking Server Responses
  48. Retrofit 2 — Customizing Network Behavior of Mocked Server Responses (soon)
  49. Java Basics for Retrofit — Callbacks (soon)
  50. Java Basics for Retrofit — Annotations (soon)
  51. Java Basics for Retrofit — Fluent Interface with Builders (soon)

Integrate a JSON Converter

A common representation of the data received from the server is the JavaScript object notation: JSON. HTTP’s response body contains any information and Retrofit parses the data and maps it into a defined Java class. This process can be kind of tricky, especially when working with custom formatted dates, nested objects wrapped in lists, and so on …

As we’ve mentioned in our Upgrade Guide, Retrofit doesn’t ship with an integrated JSON converter anymore. We need to include the converter manually. For those of you, who already worked with Retrofit 2, you’ve probably edited your build.gradle. In case you haven’t done that yet, it’s the time to do it now:

dependencies {  
    // Retrofit & OkHttp
    compile 'com.squareup.retrofit2:retrofit:2.1.0'

    // JSON Converter
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
}

Google’s Gson is a very popular JSON converter. Almost every real-world JSON mapping can be done with the help of Gson. Once you’ve added the Gradle dependency to your project you’ve to activate it on your Retrofit instance. Only then Retrofit will consider using the converter.

Retrofit retrofit = new Retrofit.Builder()  
        .baseUrl("https://api.github.com")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

GitHubService service = retrofit.create(GitHubService.class);  

The converter dependency provides a GsonConverterFactory class. Call the created instance of that class (done via create()) to your Retrofit instance with the method addConverterFactory(). After you’ve added the converter to Retrofit, it’ll automatically take care of mapping the JSON data to your Java objects, as you’ve seen in the previous blog post. Of course, this works for both directions: sending and receiving data.

The advantage of Gson is that it usually needs no setup in your Java classes. Nevertheless, there are notations for some edge cases. If your app requires Gson to do something special, head over to the Gson project to look up the details.

Customize Your Gson Configuration

We want you to know that Gson has plenty of configuration options. Please go through the official User Guide, if you want to get an overview over all the options.

The good news is that Retrofit makes it very easy to customize Gson. You don’t even need to implement your own custom converter, which we’ll look at later in another blog post. In the previous section, we’ve explained that you can add the Gson converter like this:

Retrofit retrofit = new Retrofit.Builder()  
        .baseUrl("https://api.github.com")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

We didn’t tell you, that you can pass a Gson instance to the GsonConverterFactory.create() method. Here’s an example with various Gson configurations:

 Gson gson = new GsonBuilder()
     .registerTypeAdapter(Id.class, new IdTypeAdapter())
     .enableComplexMapKeySerialization()
     .serializeNulls()
     .setDateFormat(DateFormat.LONG)
     .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
     .setPrettyPrinting()
     .setVersion(1.0)
     .create();

Retrofit retrofit = new Retrofit.Builder()  
     .baseUrl("https://api.github.com")
     .addConverterFactory(GsonConverterFactory.create(gson))
     .build();

If you pass a Gson instance to the converter factory, Retrofit will respect all of your configurations. This makes it very easy to do the fine-tuning of your JSON mapping with Gson, while keeping the actual code changes to a minimum.

Outlook

In this blog post, you've learned how to add Gson as a JSON converter to Retrofit 2. Additionally, you've seen how you can utilize the wide array of options of Gson. Retrofit makes it very easy to customize the Gson mapping rules.


Explore the Library

Find interesting tutorials and solutions for your problems.

Miscellaneous