首先sql查询出的数据结构必须包含自己与自己的父级,
sql查询出的数据封装到下面实体类:
@Data//此注解是lombok的注解,可以帮我们生成setter、getter方法
@NoArgsConstructor//lombok注解,生成无参构造
@AllArgsConstructor//lombok注解,生成有参构造
@ApiModel(value = “CustomerMenuPO”, description = “菜单查看类”)//swagger注解
public class CustomerMenuPO {
private String permId;//自己的id
private String pPermId;//父级id
private String permName;//名称
}
//工具类
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSONArray;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSONObject;
/**
-
Classname JsonUtil
-
Package cn.com.njits.api.util
-
Description //TODO
-
Company www.njits.com.cn
-
@author songyh
-
@version 1.0
-
@date 2018/10/9 14:26
*/
public class JsonUtil {/**
- listToTree
-
方法说明
- 将JSONArray数组转为树状结构
- @param arr 需要转化的数据
- @param id 数据唯一的标识键值
- @param pid 父id唯一标识键值
- @param child 子节点键值
- @return JSONArray
*/
public static JSONArray listToTree(JSONArray arr, String id, String pid, String child){
JSONArray r = new JSONArray();
JSONObject hash = new JSONObject();
//将数组转为Object的形式,key为数组中的id
for(int i=0;i<arr.size();i++){
JSONObject json = (JSONObject) arr.get(i);
hash.put(json.getString(id), json);
}
//遍历结果集
for(int j=0;j<arr.size();j++){
//单条记录
JSONObject aVal = (JSONObject) arr.get(j);
//在hash中取出key为单条记录中pid的值
JSONObject hashVP = (JSONObject) hash.get(aVal.get(pid).toString());
//如果记录的pid存在,则说明它有父节点,将她添加到孩子节点的集合中
if(hashVP!=null){
//检查是否有child属性
if(hashVP.get(child)!=null){
JSONArray ch = (JSONArray) hashVP.get(child);
ch.add(aVal);
hashVP.put(child, ch);
}else{
JSONArray ch = new JSONArray();
ch.add(aVal);
hashVP.put(child, ch);
}
}else{
r.add(aVal);
}
}
return r;
}
}
SpringBoot框架中的实现类:
/**
* 菜单树
*
* @return
*/
public JSONArray findMenuTree() {
//sql查询数据封装
List<CustomerMenuPO> menus = customerRoleMapper.findMenuTree();
if (CollectionUtils.isNotEmpty(menus)) {
//利用工具类组装到树,返回一个JSONArray
return JsonUtil.listToTree(JSONArray.parseArray(JSON.toJSONString(menus)), "permId", "pPermId", "childs");
} else {
return null;
}
}
//控制器
@ApiOperation(“系统设置-菜单树”)
@GetMapping(“menuTree/find”)
public ResultEntity findMenuTree() {
JSONArray menuTree = customerRoleService.findMenuTree();
ResultEntity success = ResultEntity.success(menuTree);
return success;
}