代码之家  ›  专栏  ›  技术社区  ›  Guilherme Lima Pereira

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

  •  11
  • Guilherme Lima Pereira  · 技术社区  · 9 年前
    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 回复  |  直到 9 年前
        1
  •  42
  •   stkent    8 年前

    (最初的答案是OkHttp版本2.5.0)。

    代替

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

    具有

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

    response.body 返回一个 ResponseBody 对象,它有自己的 string 方法:查看源 here .

        2
  •  1
  •   Tomer Shetah Anshul Jain    4 年前

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

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