如何从JSON数组中获取列的总和

时间:2017-09-14 00:28:10

标签: java arrays json

这是我的StringRequest上的Response.Listener。

                try {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray array = jsonObject.getJSONArray("cart");
                        for (int i = 0; i<array.length(); i++){
                            JSONObject o = array.getJSONObject(i);
                            CartItem item = new CartItem(
                                    o.getString("cardno"),
                                    o.getString("product_id"),
                                    o.getString("name"),
                                    o.getString("quantity"),
                                    o.getString("price"),
                                    o.getString("category")
                            );
                            cartItems.add(item);
                        }
                        adapter = new CartAdaptor(cartItems, getContext());
                        recyclerView.setAdapter(adapter);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

它将获取JSON数组并将其放入我的CartItem.java并填充我的CartAdaptor.java

public CartItem(String cardno, String product_id, String name, String quantity, String price, String category) {
    this.cardno = cardno;
    this.product_id = product_id;
    this.name = name;
    this.quantity = quantity;
    this.price = price;
    this.category = category;

如何计算该数组中的所有价格?

1 个答案:

答案 0 :(得分:1)

我不确定你想要在哪里得到总价。

我建议一个。

            try {
                    int total = 0;                         //  add this

                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray array = jsonObject.getJSONArray("cart");
                    for (int i = 0; i<array.length(); i++){
                        JSONObject o = array.getJSONObject(i);
                        CartItem item = new CartItem(
                                o.getString("cardno"),
                                o.getString("product_id"),
                                o.getString("name"),
                                o.getString("quantity"),
                                o.getString("price"),
                                o.getString("category")
                        );
                        cartItems.add(item);

                        //  add this
                        if(o.getString("price") != null &&
                           o.getString("price") != "" ){
                            total += Integer.parseInt(o.getString("price"));
                        }


                    }
                    adapter = new CartAdaptor(cartItems, getContext());
                    recyclerView.setAdapter(adapter);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
然后你可以得到总价。