使用 Retrofit v2.0.0-beta1 转换为 JSONObject / JSONArray

Convert to JSONObject / JSONArray with Retrofit v2.0.0-beta1

我目前正在升级到 Retrofit v.2.0.0-beta1,在 the docs 中它说:

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.

我究竟该如何添加一个 GSON 转换器,而不是 RequestBody 我收到 GSON.JsonObjectGSON.JsonArray 用于 Content-type: application/json 的响应?

我的初始化代码如下所示:

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);

从 Retrofit2 开始,它不会附带默认转换器,因此您需要明确添加一个转换器。

你可以这样添加。

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

并且您可以通过以下任一方式获取映射对象

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

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

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

同时添加依赖项 compile 'com.squareup.retrofit:converter-gson:2.0.0-beta1'

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