如何从OkHttp Response对象中提取原始JSON字符串?

时间:2015-09-16 00:57:21

标签: android json okhttp

private static final String URL = "http://www.livroandroid.com.br/livro/carros/carros_{tipo}.json";

public static List<Carro> getCarros(Context context, String tipo) throws IOException {
    String url = URL.replace("{tipo}", tipo);
    OkHttpClient okHttpClient = new OkHttpClient();
    Request request = new Request.Builder()
            .url(URL)
            .build();
    Response response = okHttpClient.newCall(request).execute();
    String json = response.body().toString();
    List<Carro> carros = parserJSON(context, json);
    return carros;
}

如果在调用json方法时打印出getCarros变量的值,我会在logcat中看到以下消息:

  

com.squareup.okhttp.internal.http.RealResponseBody@1e11866

如何记录我收到的实际JSON字符串?

2 个答案:

答案 0 :(得分:19)

(最初回答OkHttp版本2.5.0)。

替换

String json = response.body().toString();

String json = response.body().string();

response.body会返回ResponseBody个对象,该对象有自己的string方法:请参阅来源here

答案 1 :(得分:0)

kotlin 用户尝试此代码 100% 测试

val result: String = Gson().toJson(response.body()!!.string())