How To Get Json Object Without Converting In Retrofit 2.0?
Solution 1:
Simply use JsonElement
as your pojo. For example
In your FlowerApi interafce:
@GET("/flower")
Call<JsonElement> getFlowers();
In your main class:
Call<JsonElement> getFlowersCall = httpApiClass.getFlowers();
getFlowersCall.enqueue(newCallback<JsonElement>() {
@OverridepublicvoidonResponse(Response<JsonElement> response, Retrofit retrofit) {
JsonElement jsonElement = response.body();
Log.d(TAG, jsonElement.toString());
}
@OverridepublicvoidonFailure(Throwable t) {
Log.d(TAG, "Failed: " + t.getMessage());
}
});
Actually, the response is still converted to JsonElement
by the Gson converter, but you can get something that is close to the raw response.
Solution 2:
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);
Solution 3:
We can get JsonObject (com.google.gson) and parse this as well as standard JSONObject (org.json)
Interface FlowerApi
@GET("/flower")
Call<JsonObject> getFlowers();
In rest handler use
FlowerApiapi= ApiFactory.createRetrofitService(FlowerApi.class);
Call<JsonObject> call = api.getFlowers();
retrofit.Responseresponse= call.execute();
if (response.isSuccess()) {
JsonObjectobject= (JsonObject) response.body();
}
Api Factory class help a create retrofit service easy
publicclassApiFactory {
privatestaticfinalintTIMEOUT=60;
privatestaticfinalintWRITE_TIMEOUT=120;
privatestaticfinalintCONNECT_TIMEOUT=10;
privatestaticfinalOkHttpClientCLIENT=newOkHttpClient();
privatestaticfinalStringBASE_URL="flowers.com";
static {
CLIENT.setConnectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);
CLIENT.setWriteTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS);
CLIENT.setReadTimeout(TIMEOUT, TimeUnit.SECONDS);
}
@NonNullpublicstatic <S> S createRetrofitService(Class<S> serviceClass) {
return getRetrofit().create(serviceClass);
}
@NonNullprivatestatic Retrofit getRetrofit() {
returnnewRetrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(CLIENT)
.build();
}
}
In 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'
Post a Comment for "How To Get Json Object Without Converting In Retrofit 2.0?"