java中从josn中取出相同key所对应的另一个key的集合
json:[{'id':1,'type':role},{'id':2,'type':role},{'id':1,'type':org},{'id':2,'type':or...
json:[
{'id':1,'type':role},
{'id':2,'type':role},
{'id':1,'type':org},
{'id':2,'type':org}
]
要分别得到type=role的id集合 和type=org的id集合 存成map形式,怎么弄啊,跪求 展开
{'id':1,'type':role},
{'id':2,'type':role},
{'id':1,'type':org},
{'id':2,'type':org}
]
要分别得到type=role的id集合 和type=org的id集合 存成map形式,怎么弄啊,跪求 展开
展开全部
public static void main(String[] args)
{
String string = "[{\"depid\":\"5\",\"score\":\"10\"},{\"depid\":\"4\",\"score\":\"40\"},{\"depid\":\"4\",\"score\":\"30\"},{\"depid\":\"5\",\"score\":\"30\"}]";
JSONArray fromObject = JSONArray.fromObject(string);
Map<String,Integer> map = new HashMap<String, Integer>();
for (Object object : fromObject)
{
JSONObject jsonObject = (JSONObject) object;
String depid = (String)jsonObject.get("depid");
Integer score = Integer.valueOf((String)jsonObject.get("score"));
if (map.containsKey(depid))
{
int integer = map.get(depid);
map.put(depid, integer+score);
}
else
{
map.put(depid, score);
}
}
Set<Entry<String, Integer>> entrySet = map.entrySet();
JSONArray jsonArray = new JSONArray();
for (Entry<String, Integer> entry : entrySet)
{
JSONObject jsonObject = new JSONObject();
jsonObject.put("depid",entry.getKey());
jsonObject.put("score",String.valueOf(entry.getValue()));
jsonArray.add(jsonObject);
}
System.out.println(jsonArray.toString());
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询