gpt4 book ai didi

android - 在 "org.json.JSONException: Value{data}"中获取 JSONArray 结果

转载 作者:行者123 更新时间:2023-11-29 23:19:00 25 4
gpt4 key购买 nike

我正在使用 Volley 来请求 unsplash API,但是当我尝试以 JsonObjectRequest 请求它时,它没有给我任何错误,但我知道这是一种错误的方法,因为我收到的数据是 JSONArray

我的方法

JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Request.Method.GET,
URL,
null,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
if(response!=null){
// Process the JSON
try{
// Loop through the array elements
for (int i = 0; i < response.length(); i++) {
JSONObject js = response.getJSONObject(i);
Log.d("TESTING",js.getString("id"));
}
p.dismiss();
}catch (JSONException e){
e.printStackTrace();
}
}}
},
new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error){
Log.d("TESTING",error.getMessage());
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);

日志由于 JSONArray 太大而无法在此处发布,因此这是 formate

D/TESTING: org.json.JSONException: Value {"total": 44760,
"total_pages": 4476,
"results":[{JSONObjects}]}

如果您想在此处查看 JSONArray,请访问“https://api.unsplash.com/search/photos?query=wood&client_id=ACESS_KEY_REQUIRED

我也看过this问题,但那是完全不同的

您只需创建一个帐户即可申请 key here .

最佳答案

您需要先创建 jsonObject。您请求了 JSONArray,但您的服务器响应为 JSONObject。尝试使用 StringRequest 获取 JSONObject

试试这个:

    StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {

try {
// Loop through the array elements
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject js = jsonArray.getJSONObject(i);
Log.d("TESTING", js.getString("id"));
}
p.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}

}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("TESTING",error.getMessage());
}
})
};

RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);

希望这会奏效。

关于android - 在 "org.json.JSONException: Value{data}"中获取 JSONArray 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54766033/

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