如何从OkHttp Response对象提取原始JSON字符串? [英] How can I extract the raw JSON string from an OkHttp Response object?

查看:1075
本文介绍了如何从OkHttp Response对象提取原始JSON字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;
}

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

If I print out the value of the json variable when calling the getCarros method, I see the following message in my logcat:

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

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

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

How can I log the actual JSON string I received instead?

推荐答案

(最初针对OkHttp 2.5.0版回答).

(Originally answered for OkHttp version 2.5.0).

替换

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

使用

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

response.body返回一个ResponseBody对象,该对象具有其自己的string方法:请参见源代码

response.body returns a ResponseBody object, which has its own string method: see the source here.

这篇关于如何从OkHttp Response对象提取原始JSON字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆