@SuppressWarnings("unchecked")
public static List<Map<String, Object>> getJsonTree(List<?> source) {
Map<String, Map<String, Object>> sourceMap = convert2Map(source);
List<Map<String, Object>> resultList = new ArrayList<>();
Set<String> keySet = sourceMap.keySet();
for (String key : keySet) {
String parentKey = sourceMap.get(key).get("parentId").toString();
Map<String, Object> parent = sourceMap.get(parentKey);
if (parent != null) {
List<Object> childs = (List<Object>) parent.get("children");
childs.add(sourceMap.get(key));
parent.put("child", childs);
}
}
for(String key : keySet){
String parentKey = sourceMap.get(key).get("parentId").toString();
Map<String, Object> parent = sourceMap.get(parentKey);
if (parent == null) {
resultList.add(sourceMap.get(key));
}
}
return resultList;
}
private static Map<String, Map<String, Object>> convert2Map(List<?> source) {
Map<String, Map<String, Object>> resultMap = new HashMap<>();
for (Object s : source) {
Map<String, Object> childMap = JacksonUtil.read2Map(s.toString());
childMap.put("children", new ArrayList<Object>());
resultMap.put(childMap.get("id").toString(), childMap);
}
return resultMap;
}
转载请注明原文地址: https://ju.6miu.com/read-668388.html