OkHttp如何获得Json字符串?

Hai*_*ang 47 java http embedded-jetty okhttp

解决方案:这是我的错误.

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

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

{"employees":[
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}
Run Code Online (Sandbox Code Playgroud)

它显示在将URL输入浏览器时,不幸的是,当我请求时,它显示的是除了json字符串之外的那种内存地址Okhttp.

TestActivity? com.squareup.okhttp.internal.http.RealResponseBody@537a7f84
Run Code Online (Sandbox Code Playgroud)

Okhttp代码我使用:

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();
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮忙吗?

小智 91

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

示例添加到您的列:

JCol employees  = new employees();
colums.Setid(object.getInt("firstName"));
columnlist.add(lastName);           
Run Code Online (Sandbox Code Playgroud)

  • 很容易的错误是将`.string()`与'.toString()'混淆 (11认同)
  • 我现在得到异常:`org.json.JSONException:类型为java.lang.String的值okhttp3.internal.http.RealResponseBody@aeb56f3无法转换为JSONObject` (8认同)
  • 您应该指定从中获取对象的位置,例如JSONObject.请,也包括进口. (6认同)

小智 16

我也遇到了同样的问题

使用此代码:

// notice string() call
String resStr = response.body().string().toString();    
JSONObject json = new JSONObject(resStr);
Run Code Online (Sandbox Code Playgroud)

它确实有效


小智 12

正如我在代码中观察到的那样.如果从Response获取了body的值,则它变为空白.

String str = response.body().string();  // {response:[]}

String str1  = response.body().string();  // BLANK
Run Code Online (Sandbox Code Playgroud)

所以我相信在从身体获取一次价值后,它变得空洞.

建议:将其存储在String中,可以多次使用.


Kig*_*lip 5

我希望你设法从json字符串中获取json数据.

好吧,我觉得这会有所帮助

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");

//define the strings that will temporary store the data
String fname,lname;

//get the length of the json array
int limit = Jarray.length()

//datastore array of size limit
String dataStore[] = new String[limit];

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

    fname = object.getString("firstName");
    lname = object.getString("lastName");

    Log.d("JSON DATA", fname + " ## " + lname);

    //store the data into the array
    dataStore[i] = fname + " ## " + lname;
}

//prove that the data was stored in the array      
 for (String content ; dataStore ) {
        Log.d("ARRAY CONTENT", content);
    }
Run Code Online (Sandbox Code Playgroud)

记得使用AsyncTask或SyncAdapter(IntentService),以防止获得NetworkOnMainThreadException

还要在build.gradle中导入okhttp库

compile 'com.squareup.okhttp:okhttp:2.4.0'