定义json字符串
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" +
"]";
解决方式如下:
方法1:
方法1:
JSONArray jsonArray = JSONArray.fromObject(sourceStr);
//JSONArray data = JSONArray.parseArray(sourceStr);
Map<String, List<JSONObject>> map = new HashMap<String, List<JSONObject>>();
String tempIdStr = "";
List<JSONObject> list = null;
for(Object obj : jsonArray){
JSONObject jsonObject = (JSONObject) obj;
tempIdStr = jsonObject.getString("id");
if(map.containsKey(tempIdStr)){
list = map.get(tempIdStr);
list.add(jsonObject);
}else{
list = new ArrayList<JSONObject>();
list.add(jsonObject);
map.put(tempIdStr, list);
}
}
List targetList = new ArrayList();
Map targetMap = null;
for(Map.Entry<String, List<JSONObject>> entry : map.entrySet()){
targetMap = new HashMap();
targetMap.put("id", entry.getKey());
targetMap.put("data", entry.getValue());
targetList.add(targetMap);
}
System.out.println(targetList);
方法1输出结果如下所示:
//方法1 输出结果:
[{id=1001, data=[{"id":"1001","name":"测试1","value":"111"}]}, {id=1002, data=[{"id":"1002","name":"测试2","value":"222"}, {"id":"1002","name":"测试2","value":"22222"}]}, {id=1002, data=[{"id":"1002","name":"测试2","value":"2222222"}, {"id":"1003","name":"测试3","value":"333"}, {"id":"1003","name":"测试3","value":"333333"}]}]
方法2:
方法2:
JSONArray data1=JSONArray.fromObject(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()) {
System.out.println(id +":"+dataMap.get(id));
}
方法2输出结果如下所示:
//方法2 输出结果
1001:[{"id":"1001","name":"测试1","value":"111"}]
1003:[{"id":"1003","name":"测试3","value":"333"}, {"id":"1003","name":"测试3","value":"333333"}]
1002:[{"id":"1002","name":"测试2","value":"222"}, {"id":"1002","name":"测试2","value":"22222"}, {"id":"1002","name":"测试2","value":"2222222"}]