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());
本文介绍了一种使用 Java 对 JSON 数组中的数据进行聚合的方法。通过对 JSON 对象的遍历和 Map 的运用,实现了对相同名称的数据项数值求和,并最终将处理后的结果转换为新的 JSON 数组输出。
753

被折叠的 条评论
为什么被折叠?



