我有很多对象的json api,我想在提供密钥后将数据存储在Map中。然后我想稍后使用该地图列表。下面是我想要的方式。



Map<Integer, Integer> maplist; /// globle variable
//// inside response method inside the for loop

   maplist = new HasMap<>();

maplist.put(10, 1);
//////.....
........

最佳答案

你可以做这样的事情。下面是示例代码



    public void getQtyReserved() {
        JsonObjectRequest request_json = new JsonObjectRequest(Request.Method.GET, cart_url + name, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                       listMap = new HashMap<Integer, Integer>();
                        try {
                            JSONArray ja_data = response.getJSONArray("list");
                            int length = ja_data.length();


                            for (int i = 0; i < length; i++) {
                                JSONObject jsonobject = ja_data.getJSONObject(i);

                                int quantity_reserved = jsonobject.getInt("quantity_reserved");
                                int inventory_id = jsonobject.getInt("inventory_id");

                     listMap.put(inventory_id, quantity_reserved);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.e("Error: ", error.getMessage());
                Toast.makeText(getApplicationContext(), "its empty", Toast.LENGTH_LONG).show();
            }
        });
        MySingleton.mySingletonInstance(getApplicationContext()).addToRequestque(request_json);
    }

关于android - 如何使用Volley发送http get请求并将数据存储到Maps with Keys?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45925813/

10-10 00:05