改造2.0如何打印完整的json响应? [英] retrofit 2.0 how to print the full json response?
问题描述
我现在从Volley转到Retrofit 2.0版。
I am moving from Volley to Retrofit currently version 2.0.
如何打印完整的json响应代码?
How to print the the full json response code ?
包含:
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
RestClient :
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
return response;
}
});
Gson gson = new GsonBuilder()
.setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'")
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ROOT)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(client)
.build();
REST_CLIENT = retrofit.create(APIService.class);
APIService :
@GET("my/json")
Call<Model> getFeed();
在活动中 - 调用API :
Call<Model> call = RestClient.get().getFeed();
call.enqueue(new Callback<Model>() {
@Override
public void onResponse(Response<Model> response, Retrofit retrofit) {
Log.w("2.0 getFeed > response.raw() => ", response.raw().toString());//DONT WORK
Log.w("2.0 getFeed > retrofit => ", retrofit.toString());//DONT WORK
Log.w("2.0 getFeed > body => ", response.body().toString()); //DONT WORK
Log.w("2.0 getFeed > getStatus => ", response.body().getStatus());
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
Log.e("2.0 getFeed > onFailure => ", t.toString());
}
});
推荐答案
要在json中打印完整的响应:
To print the full response in json:
Log.w("2.0 getFeed > Full json res wrapped in gson => ",new Gson().toJson(response));
如果您想要漂亮的打印功能,请使用:
If you'd like to have pretty print feature, use:
Log.w("2.0 getFeed > Full json res wrapped in pretty printed gson => ",new GsonBuilder().setPrettyPrinting().create().toJson(response));
请注意,这会打印反序列化数据(而不是从服务器返回的Raw响应)。要获得原始响应,您需要处理 HttpLoggingInterceptor
或拥有自己的拦截器版本。使用http debuf工具的其他方法,例如 Stetho
或 Charles Web Debugging Proxy
。
Note that this prints the deserialized data (not Raw response as returned from server). To get the raw response, you would need to deal with HttpLoggingInterceptor
or have your own version of interceptor. Other approach to use http debuf tools such as Stetho
or Charles Web Debugging Proxy
.
这篇关于改造2.0如何打印完整的json响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!