android - 获取 JSONArray 结果为“org.json.JSONException: Value{data}”
问题描述
我正在使用 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 太大,无法在此处发布,这是格式
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
”
我也看过这个问题,但这完全不同
您只需在此处注册一个帐户即可请求密钥。
解决方案
您需要先创建 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);
希望这会奏效。
推荐阅读
- java - 非 android 模块清理架构设置中的 Hilt
- c++ - unique_ptr 两次调用析构函数
- docusaurus - Docusaurus v2 - Nav Dropdown 中的文档链接,没有版本控制
- android - 使用 Alpakka 发送具有高优先级的 Firebase 通知
- excel - 无法弄清楚为什么 VBA 在验证 If 语句时退出我的 For-Next 循环
- rust - Rust 闭包真的不需要类型注解吗?
- monaco-editor - 自定义现有的操作快捷方式
- php - 删除项目后在 php 中索引 JSON
- vue.js - 如何输入一个点“。” 在价格输入字段中手动
- c# - 如何将程序集动态加载到我的 C# 程序中,.NET Framework 4.7