一、SQL
SELECT
categoryCode AS 'id',
categoryName AS 'label',
parentCode AS 'parentId'
FROM
a
二、JAVA代码
/**
* 创建树形结构菜单列表
*
* @param menus
* @return
*/
public static List<PlaCategoryTreeDto> createTreeMenus(List<PlaCategoryTreeDto> menus) {
List<PlaCategoryTreeDto> treeMenus = null;
//判断非空
if (null != menus && !menus.isEmpty()) {
// 创建根节点
PlaCategoryTreeDto root = new PlaCategoryTreeDto();
root.setLabel("菜单根目录");
// 组装Map数据
Map<String, PlaCategoryTreeDto> dataMap = new HashMap<>();
for (PlaCategoryTreeDto menu : menus) {
dataMap.put(menu.id, menu);
}
// 组装树形结构
Set<Map.Entry<String, PlaCategoryTreeDto>> entrySet = dataMap.entrySet();
//foreach遍历
for (Map.Entry<String, PlaCategoryTreeDto> entry : entrySet) {
PlaCategoryTreeDto menu = entry.getValue();
//判断是父节点还是子节点
if (StringUtil.isEmpty(menu.getParentId()) || "1".equals(menu.getParentId())) {
//父节点
if (root.getChildren() == null) {
//子节点为空
List<PlaCategoryTreeDto> tempList = new ArrayList<>();
tempList.add(menu);
root.setChildren(tempList);
} else {
//子节点不为空
root.getChildren().add(menu);
}
} else {
//子节点
PlaCategoryTreeDto parentMenu = dataMap.get(menu.getParentId());
//如果为null说明父级节点不显示,则对应的子级节点也不显示
if (parentMenu != null) {
if (parentMenu.getChildren() == null) {
//子节点为空
List<PlaCategoryTreeDto> tempList = new ArrayList<>();
tempList.add(menu);
dataMap.get(menu.getParentId()).setChildren(tempList);
} else {
//子节点不为空
dataMap.get(menu.getParentId()).getChildren().add(menu);
}
}
}
}
treeMenus = root.getChildren();
}
return treeMenus;
}
三、JSON
{
"body": {
"data": [
{
"id": "0217fb7d-03ef-4a91-ac12-30720e170f5d",
"label": "数码产品",
"parentId": "1",
"children": [
{
"id": "fc5e438f-cd13-4d55-93aa-7ce7ab9777f6",
"label": "相机",
"parentId": "0217fb7d-03ef-4a91-ac12-30720e170f5d",
"children": null
}
]
},
{
"id": "b9cc292d-02df-41d9-8f4d-f376c8b9613c",
"label": "服装",
"parentId": "1",
"children": [
{
"id": "3129f97b-4ffe-4740-8654-7b7a92468598",
"label": "男装",
"parentId": "b9cc292d-02df-41d9-8f4d-f376c8b9613c",
"children": null
},
{
"id": "b2db9dd3-9a93-453c-a4d8-9d376875cda4",
"label": "女装",
"parentId": "b9cc292d-02df-41d9-8f4d-f376c8b9613c",
"children": null
},
{
"id": "ec83d829-5f8e-47fb-a6eb-4841845d68e8",
"label": "童装",
"parentId": "b9cc292d-02df-41d9-8f4d-f376c8b9613c",
"children": null
}
]
}
]
}
}