【问题标题】:Not able to fetch JSON data [using volley Library] in Android无法在 Android 中获取 JSON 数据 [使用 volley Library]
【发布时间】:2020-05-11 10:59:14
【问题描述】:

jason 数组请求代码如下:

     JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.GET,url, (JSONArray) null , new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                try {
                    Log.d("Response:", String.valueOf(response.getJSONObject(0)));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(context, "Response not recieved", Toast.LENGTH_SHORT).show();
            }
        });

我使用了请求队列的单例实例来获取数据,

AppController.getInstance(context.getApplicationContext()).addToRequestQueue(arrayRequest);

我正在使用一个提供一堆问题的api服务(api生成一个url,它返回一个json对象的集合,一个数组(只需尝试打开url链接,就会看到json数组)

但是当我运行应用程序时,请求甚至没有得到响应,程序流进入错误列表块。

有人可以解释这种行为吗?是不是因为 url 提供的 JSON 数组有嵌套数组?为什么?

我尝试在这里阅读和分析其他问题,可能有同样的问题,但我什么也没找到。

【问题讨论】:

标签: android arrays json android-volley


【解决方案1】:

您只想将 JsonArrayRequest 更改为 JsonObjectRequest

请复制粘贴以下代码:

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
                url, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("TAG", response.toString());

                        try {
                            JSONArray jsonArray = response.getJSONArray("results");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);

                                String category = jsonObject.getString("category");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d("TAG", "Error: " + error.getMessage());
                // hide the progress dialog
            }
        });

        AppController.getInstance().addToRequestQueue(jsonObjReq, "TAG"); 

点击此链接了解其他请求:Androidhive

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    相关资源
    最近更新 更多