package app.util; import java.util.ArrayList; import java.util.List; import com.alibaba.fastjson.JSON; public class Menu { private Integer pid; private String menuName; private Integer parentId; private Integer position; private List<Menu> childMenu; public Integer getPid() { return pid; } public void setPid(Integer pid) { this.pid = pid; } public String getMenuName() { return menuName; } public void setMenuName(String menuName) { this.menuName = menuName; } public Integer getParentId() { return parentId; } public void setParentId(Integer parentId) { this.parentId = parentId; } public Integer getPosition() { return position; } public void setPosition(Integer position) { this.position = position; } public List<Menu> getChildMenu() { return childMenu; } public void setChildMenu(List<Menu> childMenu) { this.childMenu = childMenu; } public Menu(Integer parentId,String menuName, Integer pid, Integer position) { super(); this.parentId = parentId; this.menuName = menuName; this.pid = pid; this.position = position; } public Menu() { super(); } public static void main(String[] args) { List<Menu> list=new ArrayList<Menu>(); Menu menu1=new Menu(1, "父级1", 0, 1); Menu menu2=new Menu(2, "父级2", 0, 2); Menu menu1_1=new Menu(3, "子级1_1", 1, 1); Menu menu1_2=new Menu(4, "子级1_2", 1, 2); Menu menu1_2_1=new Menu(5, "子级1_2_1", 4, 2); Menu menu1_2_2=new Menu(6, "子级1_2_2", 2, 2); list.add(menu1); list.add(menu2); list.add(menu1_1); list.add(menu1_2); list.add(menu1_2_1); list.add(menu1_2_2); List<Menu> listTree=buildTree(list,0); String trssJson=JSON.toJSONString(listTree); System.out.println(trssJson); } public static List<Menu> buildTree(List<Menu> list,int pid){ List<Menu> menus=new ArrayList<Menu>(); for (Menu menu : list) { int parentId = menu.getPid(); int menuId= menu.getParentId(); if (pid == parentId) { List<Menu> menuLists = buildTree(list, menuId); menu.setChildMenu(menuLists); menus.add(menu); } } return menus; } }
成型
[ { "childMenu": [ { "childMenu": [ ], "menuName": "子级1_1", "parentId": 3, "pid": 1, "position": 1 }, { "childMenu": [ { "childMenu": [ ], "menuName": "子级1_2_1", "parentId": 5, "pid": 4, "position": 2 } ], "menuName": "子级1_2", "parentId": 4, "pid": 1, "position": 2 } ], "menuName": "父级1", "parentId": 1, "pid": 0, "position": 1 }, { "childMenu": [ { "childMenu": [ ], "menuName": "子级1_2_2", "parentId": 6, "pid": 2, "position": 2 } ], "menuName": "父级2", "parentId": 2, "pid": 0, "position": 2 } ]