对key值相同的json数据进行相加合并

 ja:[{"name":"AA","num":"2"},{"name":"AA","num":"3"},{"name":"BB","num":"4"},{"name":"BB","num":"2"}]

JSONArray ja = new JSONArray();

Map<String,Integer> map = new HashMap<String, Integer>();

for (Object object : ja)

        {

            JSONObject jsonObject = (JSONObject) object;

            String name = (String)jsonObject.get("name");

            Integer num = Integer.valueOf((String)jsonObject.get("num"));

            if (map.containsKey(name))

            {

                int integer = map.get(name);

                map.put(name, integer+num);

            }

            else

            {

                map.put(name, num);

            }

        }

        Set<Entry<String, Integer>> entrySet = map.entrySet();

        JSONArray jsonArray = new JSONArray();

         

        for (Entry<String, Integer> entry : entrySet)

        {

            JSONObject jsonObject = new JSONObject();

            jsonObject.put("name",entry.getKey());

            jsonObject.put("num",String.valueOf(entry.getValue()));

            jsonArray.add(jsonObject);

        }

        System.out.println(jsonArray.toString());

猜你喜欢

转载自644640918.iteye.com/blog/2317308