首页 > 解决方案 > 获取 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

我也看过这个问题,但这完全不同

您只需在此处注册一个帐户即可请求密钥。

标签: androidarraysjson

解决方案


您需要先创建 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);

希望这会奏效。


推荐阅读