将JsonArray按某一个字段分组成多个JsonArray的方法
作者:互联网
String sourceStr = "[\n" + " {\"id\":\"1001\",\"name\":\"测试1\",\"value\":\"111\"},\n" + " {\"id\":\"1002\",\"name\":\"测试2\",\"value\":\"222\"},\n" + " {\"id\":\"1002\",\"name\":\"测试2\",\"value\":\"22222\"},\n" + " {\"id\":\"1002\",\"name\":\"测试2\",\"value\":\"2222222\"},\n" + " {\"id\":\"1003\",\"name\":\"测试3\",\"value\":\"333\"},\n" + " {\"id\":\"1003\",\"name\":\"测试3\",\"value\":\"333333\"}\n" + "]"; JSONArray data1=JSONArray.parseArray(sourceStr); Map<String, List<?>> dataMap = new HashMap<String, List<?>>(); //数据分组算法 for (int i = 0; i < data1.size(); i++) { JSONObject json = (JSONObject)data1.get(i); List<Object> tempList = (List<Object>) dataMap.get(json.get("id")); if(tempList == null) { //第一次则创建list tempList = new ArrayList<>(); tempList.add(json); dataMap.put(json.get("id").toString(), tempList);//放入map中 }else { tempList.add(json); } } //遍历 for (String id: dataMap.keySet()) { JSONArray objects = JSONArray.parseArray(JSON.toJSONString(dataMap.get(id))); System.out.println(objects.toString()); }
标签:name,多个,get,JsonArray,json,value,字段,id,tempList 来源: https://www.cnblogs.com/void--main/p/16594846.html