OkHttp如何获取Json字符串?

2022-08-31 13:36:01

解决方案:这是我这边的错误。

正确的方法是 response.body().string() 而不是 response.body.toString()

我使用Jetty servlet,URL是,每次请求这个URL都会返回http://172.16.10.126:8789/test/path/jsonpage

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

当我在浏览器中键入url时,它会显示出来,不幸的是,当我用.请求时,它会显示json字符串以外的内存地址。Okhttp

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

Okhttp 代码 Im 使用:

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

任何人都可以帮忙吗?


答案 1
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);           

答案 2

我也面临着同样的问题

使用以下代码:

// notice string() call
String resStr = response.body().string();    
JSONObject json = new JSONObject(resStr);

它绝对有效


推荐