2

I am currently in the process of upgrading to Retrofit v.2.0.0-beta1 and in the docs it says:

By default, Retrofit can only deserialize HTTP bodies into OkHttp's ResponseBody type and it can only accept its RequestBody type for @Body.

Converters can be added to support other types. Six sibling modules adapt popular serialization libraries for your convenience.

How exactly do I add a GSON converter so instead of RequestBody I receive GSON.JsonObject or GSON.JsonArray for responses with Content-type: application/json?

My initialization code looks like this:

OkHttpClient client = new OkHttpClient();

client.interceptors().add(new AuthInterceptor(authState));
client.interceptors().add(new LoggingInterceptor());

restClient = new Retrofit.Builder()
        .client(client)
        .baseUrl(BASE_URL)
        .build()
        .create(RestClient.class);
heyarne
  • 1,127
  • 9
  • 33
  • Why do you want to receive Gson wrapper objects instead of POJOs? – durron597 Sep 01 '15 at 16:55
  • Because I would prefer to use them like a map. There are many different endpoints in the API I'm dealing with, resulting in a wide range of different types. Coming from more dynamic languages as Java, this seems to create more hassle than good to me. – heyarne Sep 01 '15 at 16:58
  • possible duplicate of [How to handle Dynamic JSON in Retrofit?](http://stackoverflow.com/questions/24279245/how-to-handle-dynamic-json-in-retrofit) – durron597 Sep 01 '15 at 17:02
  • I hope that question will help you. – durron597 Sep 01 '15 at 17:03
  • In retrofit 2, each call is a separate object and it is typed (YES!!) so you can specify what type of response object for each different endpoints. I updated with the example of how to specify type for a specific call. So instead of you get generic map and do mapping by yourself, retrofit already do that for you. – Emma Sep 02 '15 at 08:37

1 Answers1

4

Since Retrofit2, it will not come with a default converter so you need to explicitly add a converter.

You can add like this.

Retrofit retrofit = new Retrofit.Builder()
            .client(client)
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

And you can get a mapped object by either

Call<MyObject> call = myService.callMyService();
Response<MyObject> response = call.execute();
MyObject mappedObj = response.body();

or

Call<MyObject> call = myService.callMyService();
call.enqueue(new Callback<MyObject>() {
    @Override void onResponse(Response response) {
        MyObject mappedObj = response.body();
    }

    @Override void failure(Throwable throwable) {}
});

Also add dependencies compile 'com.squareup.retrofit:converter-gson:2.0.0-beta1'

Reference: https://speakerdeck.com/jakewharton/simple-http-with-retrofit-2-droidcon-nyc-2015

Emma
  • 8,518
  • 1
  • 18
  • 35