引入依赖
< dependency> < groupId> cn.hutool</ groupId> < artifactId> hutool-all</ artifactId> < version> ${hutool.version}</ version>
</ dependency>
测试
@SpringBootTest
public class HutoolTest { private List < Menu > menuList = new ArrayList < > ( ) ; @BeforeEach public void init ( ) { menuList. add ( new Menu ( 1L , 0L , "一级菜单" , 1 , "first" , LocalDateTime . now ( ) ) ) ; menuList. add ( new Menu ( 2L , 1L , "二级菜单" , 1 , "second" , LocalDateTime . now ( ) ) ) ; menuList. add ( new Menu ( 3L , 2L , "三级菜单" , 1 , "first" , LocalDateTime . now ( ) ) ) ; menuList. add ( new Menu ( 4L , 0L , "一级菜单-1" , 2 , "first-1" , LocalDateTime . now ( ) ) ) ; } @Test public void testBuildTree ( ) { TreeNodeConfig config = new TreeNodeConfig ( ) ; config. setIdKey ( "id" ) ; config. setParentIdKey ( "pid" ) ; config. setChildrenKey ( "children" ) ; config. setNameKey ( "name" ) ; config. setWeightKey ( "weight" ) ; List < Tree < Long > > treeList = TreeUtil . build ( menuList, 0L , config, new NodeParser < Menu , Long > ( ) { @Override public void parse ( Menu menu, Tree < Long > tree) { tree. setId ( menu. id) ; tree. setParentId ( menu. pid) ; tree. setName ( menu. name) ; tree. setWeight ( menu. weight) ; Map < String , Object > map = new HashMap ( ) ; map. put ( "code" , menu. code) ; map. put ( "createTime" , menu. createTime) ; tree. putAll ( map) ; } } ) ; System . out. println ( JSONUtil . toJsonStr ( treeList) ) ; } class Menu { private Long id; private Long pid; private String name; private Integer weight; private String code; private LocalDateTime createTime; public Menu ( Long id, Long pid, String name, Integer weight, String code, LocalDateTime createTime) { this . id = id; this . pid = pid; this . name = name; this . weight = weight; this . code = code; this . createTime = createTime; } }
}
结果
[{"id": 1,"pid": 0,"name": "一级菜单","code": "first","createTime": "first","children": [{"id": 2,"pid": 1,"name": "二级菜单","code": "second","createTime": "second","children": [{"id": 3,"pid": 2,"name": "三级菜单","code": "first","createTime": "first"}]}]},{"id": 4,"pid": 0,"name": "一级菜单-1","code": "first-1","createTime": "first-1"}
]