gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 07:52:53 26 4
gpt4 key购买 nike

我目前正在升级到 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 用于响应 内容类型: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) {}
});

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

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

关于android - 使用 Retrofit v2.0.0-beta1 转换为 JSONObject/JSONArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32336785/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com