首页 > 解决方案 > 如何使用 Volley 从 JSON 对象中获取数组的值?

问题描述

我有这样的json结果

知道我在 andorid studio 中的代码是这样的在此处输入图像描述

JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONObject object = response.getJSONObject("response");
                        JSONArray jsonArray = response.getJSONArray("list");
                        for (int i=0; i< jsonArray.length();i++){
                            JSONObject coba = jsonArray.getJSONObject(i);
                            String namapoli = coba.getString("namapoli");
                            mTextViewResult.append(namapoli);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });
    mQueue.add(request);
}

但为什么应用程序不显示结果?任何人都可以给我

标签: androidjson

解决方案


您正在尝试从 api 响应获取列表数组,而不是您定义的从 api 响应获取响应正文的对象:

改变 :

JSONArray jsonArray = response.getJSONArray("list");

至:

JSONArray jsonArray = object.getJSONArray("list");

最终视图将如下所示:

JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONObject object = response.getJSONObject("response");
                        JSONArray jsonArray = object.getJSONArray("list");
                        for (int i=0; i< jsonArray.length();i++){
                            JSONObject coba = jsonArray.getJSONObject(i);
                            String namapoli = coba.getString("namapoli");
                            mTextViewResult.append(namapoli);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });
    mQueue.add(request);
}

推荐阅读