使用工具类
先在po类中建立
List<类名称> children;
public class TreeUtils { public static Map<String,Object> mapArray = new LinkedHashMap<String, Object>(); public static List<MoldInfo> menuCommon; //放你的结构 public static List<Object> list = new ArrayList<>(); public static List<Object> treeMenu(List<MoldInfo> menu){ if (list!=null){//如果不进行清除第二次查询里面有两次查询的数据 list.clear(); } menuCommon = menu; for (MoldInfo treeNode : menu) { Map<String,Object> mapArr = new LinkedHashMap<String, Object>(); if(treeNode.getParentId().equals("0")){ //这边我写的是更节点默认是0 setTreeMap(mapArr,treeNode); list.add(mapArr); } } return list; } public static List<?> menuChild(String id){ List<Object> lists = new ArrayList<Object>(); for(MoldInfo a:menuCommon){ Map<String,Object> childArray = new LinkedHashMap<String, Object>(); if(a.getParentId().equals(id)){ //这里替换下父id setTreeMap(childArray,a); lists.add(childArray); } } return lists; } //写上你的类的结构 private static void setTreeMap(Map<String, Object> mapArr, MoldInfo treeNode){ mapArr.put("id", treeNode.getId()); mapArr.put("moldName", treeNode.getMoldName()); mapArr.put("label", treeNode.getMoldName()); mapArr.put("parentId", treeNode.getParentId()); mapArr.put("crtId", treeNode.getCrtId()); mapArr.put("crtTime", treeNode.getCrtTime()); mapArr.put("crtIp", treeNode.getCrtIp()); mapArr.put("updId", treeNode.getUpdId()); mapArr.put("updTime", treeNode.getUpdTime()); mapArr.put("updIp", treeNode.getUpdIp()); mapArr.put("children", menuChild(treeNode.getId())); } }
然后在controller内写调用就可以了!
结果大概是这样的
参考并借鉴:Java树形结构数据处理(递归处理)-可自由更换业务实体-TreeUitls工具类详解 - 程序员大本营 (pianshen.com)