@Data
@NoArgsConstructor
@AllArgsConstructor
public class AClothClassVo {
private Integer id;
private String name;
private Integer pid;
private String desc;
private Integer sort;
// 子目录列表
private List<AClothClassVo> treeNode;
public static void main(String[] args) {
// 构建数据
List<AClothClassVo> lists = CollUtil.newArrayList();
lists.add(new AClothClassVo(1, "顶级目录1", 0, "顶级目录", 0,null));
lists.add(new AClothClassVo(2, "一级目录1", 1, "父目录01", 1,null));
lists.add(new AClothClassVo(3, "一级目录2", 1, "父目录01", 3,null));
lists.add(new AClothClassVo(4, "一级目录3", 1, "父目录01", 2,null));
TreeNodeConfig config = new TreeNodeConfig();
// 树形数据中id的属性名,写成id1方便区分,实际上写AClothClassVo实体类的id属性名
config.setIdKey("id1");
/**
* 入参
* tree: 最终要返回的数据
* node: lists数据
*
* 返回
* Tree<String>
* Tree: 转换的实体 为数据源里的对象类型
* String: ID类型
*
*/
List<Tree<String>> list = TreeUtil.build(lists, "0", config, (node, tree) -> {
tree.setId(node.getId().toString());
tree.setName(node.getName());
tree.setParentId(node.getPid().toString());
// 根据该字段排序,正序排列,数字越小越靠前
tree.setWeight(node.getSort());
// 额外的值
tree.put("desc", node.getDesc());
tree.put("sort", node.getSort());
});
// 倒序排列,数字越大越考前
//Tree<String> stringTree = list.get(0);
//Collections.reverse(stringTree.getChildren());
System.out.println(JSON.toJSONString(list));
}
}
返回数据
[
{
"id1":"1",
"name":"顶级目录1",
"parentId":"0",
"weight":0,
"desc":"顶级目录",
"sort":0,
"children":[
{
"id1":"2",
"name":"一级目录1",
"parentId":"1",
"weight":1,
"desc":"父目录01",
"sort":1
},
{
"id1":"4",
"name":"一级目录3",
"parentId":"1",
"weight":2,
"desc":"父目录01",
"sort":2
},
{
"id1":"3",
"name":"一级目录2",
"parentId":"1",
"weight":3,
"desc":"父目录01",
"sort":3
}
]
}
]