gpt4 book ai didi

java - 从 JSON 响应中提取值

转载 作者:行者123 更新时间:2023-12-02 10:35:57 29 4
gpt4 key购买 nike

从休息服务中我收到以下 json 响应

{"code":1,"message":"success","status":"success","users":[{"email":"qqq@aa.aa","name":"qq"},{"email":"dd@dd.dd","name":"dd"},{"email":"cc@vv.vv","name":"cc"},{"email":"qq@qq.qq","name":"qq"},{"email":"qq@qq.qq","name":"qq"}]}

当我尝试将其转换为 JSONObject 时,它抛出一个错误,这就是我尝试提取 JSON 响应的方法,

jsonObject = new JSONObject(response.body().string());

上面的脚本引发了错误。错误如下,

E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
Process: com.example.ej.ziphiotest, PID: 21945
java.lang.IllegalStateException: closed
at okio.RealBufferedSource.rangeEquals(RealBufferedSource.java:408)
at okio.RealBufferedSource.rangeEquals(RealBufferedSource.java:402)
at okhttp3.internal.Util.bomAwareCharset(Util.java:432)
at okhttp3.ResponseBody.string(ResponseBody.java:174)
at com.example.ej.ziphiotest.requests.UserRequest$1.onResponse(UserRequest.java:85)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:153)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)

编辑:

这是请求:

final Request request = new Request.Builder()
.header("key", params[0])
.url(URL)
.build();

try {
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
call.cancel();
}

@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.code() == 200){
try {
jsonObject = new JSONObject(response.body().string());
restResponse = new RestResponse(jsonObject.getString("status"), jsonObject.getString("code"), jsonObject.getString("message"), null, jsonObject.getJSONArray("users"));
onTaskComplete.onTaskComplete(restResponse);
} catch (JSONException e) {
e.printStackTrace();
}
}

}
});
} catch (Exception e) {
e.printStackTrace();
}


}

我错过的地方。感谢您抽出宝贵的时间

最佳答案

问题是我在很短的时间内使用了 response.body().string() 两次。作为@Firoz Memon在评论中说。

Try storing it in a variable and then using the variable, not the response.body().string() code. Because response body can be huge so OkHttp doesn’t store it in memory, it reads it as a stream from network when you need it. When you read body as a string() OkHttp downloads response body and returns it to you without keeping reference to the string, it can’t be downloaded twice without new request.

复制自@Firoz Memon上面的评论。

原始引用:https://github.com/square/okhttp/issues/1240

关于java - 从 JSON 响应中提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53293364/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com