OkHttp如何获得Json字符串? [英] How does OkHttp get Json string?

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

问题描述

解决方案
这是我的错误。

Solution: It was a mistake on my side.

正确的方法是 response.body()。string()除了 response.body.toString()

我正在使用Jetty servlet,URL为 http://172.16.10.126:8789/test/path/jsonpage ,每次请求此URL返回时

Im using Jetty servlet, the URL ishttp://172.16.10.126:8789/test/path/jsonpage, every time request this URL it will return

{"employees":[
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

在浏览器中键入url时显示,不幸的是,当我请求时,它显示除了json字符串之外的那种内存地址code> Okhttp 。

It shows up when type the url into a browser, unfortunately it shows kind of memory address other than the json string when I request with Okhttp.

TestActivity﹕ com.squareup.okhttp.internal.http.RealResponseBody@537a7f84

Okhttp代码我使用:

The Okhttp code Im using:

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  Response response = client.newCall(request).execute();
  return response.body().string();
}

任何人都可以帮忙吗?

推荐答案

try {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
        .url(urls[0])
        .build();
    Response responses = null;

    try {
        responses = client.newCall(request).execute();
    } catch (IOException e) {
        e.printStackTrace();
    }
    String jsonData = responses.body().string();
    JSONObject Jobject = new JSONObject(jsonData);
    JSONArray Jarray = Jobject.getJSONArray("employees");

    for (int i = 0; i < Jarray.length(); i++) {
        JSONObject object     = Jarray.getJSONObject(i);
    }
}

添加到列中的示例:

JCol employees  = new employees();
colums.Setid(object.getInt("firstName"));
columnlist.add(lastName);           

这篇关于OkHttp如何获得Json字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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