簡體   English   中英

如何使用 Volley 從 JSON 對象中獲取數組的值?

[英]How to get an array's value from a JSON object by using Volley?

我有這樣的 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);
}

但為什么應用程序不顯示結果? 任何人都可以給我

您正在嘗試從 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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM