我需要从REST服务器下载json对象而不用GSON转换。但不明白如何在Retrofit 2.0 bata 1中制作
答案 0 :(得分:7)
只需使用JsonElement
作为你的pojo。例如
在你的FlowerApi interfce中:
@GET("/flower")
Call<JsonElement> getFlowers();
在你的主要课程中:
Call<JsonElement> getFlowersCall = httpApiClass.getFlowers();
getFlowersCall.enqueue(new Callback<JsonElement>() {
@Override
public void onResponse(Response<JsonElement> response, Retrofit retrofit) {
JsonElement jsonElement = response.body();
Log.d(TAG, jsonElement.toString());
}
@Override
public void onFailure(Throwable t) {
Log.d(TAG, "Failed: " + t.getMessage());
}
});
实际上,Gson转换器仍然会将响应转换为JsonElement
,但您可以获得接近原始响应的内容。
答案 1 :(得分:1)
1 compile 'io.reactivex:rxjava:1.0.+'
compile 'com.squareup.retrofit:retrofit:2.0.0-beta1'
compile 'com.squareup.retrofit:adapter-rxjava:2.0.0-beta1'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta1'
compile 'com.squareup.okhttp:okhttp:2.5.0'
compile 'com.squareup.okhttp:okhttp-urlconnection:2.5.0'
2 OkHttpClient client = new OkHttpClient();
// client.interceptors().add(new UrlInterceptor());
client.interceptors().add(new LoggingInterceptor());
AppApi api = new Retrofit.Builder()
.baseUrl("https://api.github.com")
// add a converter for String
.addConverter(String.class, new ToStringConverter())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(client)
.build()
.create(AppApi.class);
答案 2 :(得分:1)
我们可以获得 JsonObject(com.google.gson)并解析此标准 JSONObject(org.json)
界面FlowerApi
@GET("/flower")
Call<JsonObject> getFlowers();
在休息处理程序中使用
FlowerApi api = ApiFactory.createRetrofitService(FlowerApi.class);
Call<JsonObject> call = api.getFlowers();
retrofit.Response response = call.execute();
if (response.isSuccess()) {
JsonObject object = (JsonObject) response.body();
}
Api Factory类可帮助您轻松创建改造服务
public class ApiFactory {
private static final int TIMEOUT = 60;
private static final int WRITE_TIMEOUT = 120;
private static final int CONNECT_TIMEOUT = 10;
private static final OkHttpClient CLIENT = new OkHttpClient();
private static final String BASE_URL = "flowers.com";
static {
CLIENT.setConnectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);
CLIENT.setWriteTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS);
CLIENT.setReadTimeout(TIMEOUT, TimeUnit.SECONDS);
}
@NonNull
public static <S> S createRetrofitService(Class<S> serviceClass) {
return getRetrofit().create(serviceClass);
}
@NonNull
private static Retrofit getRetrofit() {
return new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(CLIENT)
.build();
}
}
在build.gradle中
compile 'com.squareup.retrofit:retrofit:2.0.0-beta1'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta1'
compile 'com.squareup.okhttp:okhttp:2.0.0'