部门结构树优化(json递归)

实体类

public class SysDept 
{
    private static final long serialVersionUID = 1L;

    /** 部门ID */
    private Long deptId;

    /** 父部门ID */
    private Long parentId;

       
    /** 子部门 */
    private List<SysDept> children = new ArrayList<SysDept>();
}

  普通list转换为treeList

 public <T> List<T> listToTreeList ( JSONArray arr , String deptId , String parentId , String children,
            Class<T> clazz )
    {
        JSONArray r = new JSONArray();
        JSONObject hash = new JSONObject();
        //将数组转为Object的形式,key为数组中的deptId
        for ( int i = 0;i < arr.size();i++ ) {
            JSONObject json = (JSONObject)arr.get(i);
            hash.put(json.getString(deptId) , json);
        }
        //遍历结果集
        for ( int j = 0;j < arr.size();j++ ) {
            //单条记录
            JSONObject aVal = (JSONObject)arr.get(j);
            //在hash中取出key为单条记录中parentId的值
            JSONObject hashVP = (JSONObject)hash.get(aVal.get(parentId).toString());
            //如果记录的parentId存在,则说明它有父节点,将她添加到孩子节点的集合中
            if ( hashVP != null ) {
                //检查是否有children属性
                if ( hashVP.get(children) != null ) {
                    JSONArray ch = (JSONArray)hashVP.get(children);
                    ch.add(aVal);
                    hashVP.put(children , ch);
                }
                else {
                    JSONArray ch = new JSONArray();
                    ch.add(aVal);
                    hashVP.put(children , ch);
                }
            }
            else {
                r.add(aVal);
            }
        }
        return r.toJavaList(clazz);
    }

s   数据库中数据结构

 

 

 

方法调用


depts 为List < SysDept > depts 数据库取出的depts
List < SysDept > list = listToTreeList(JSONArray.parseArray(JSON.toJSONString(depts)) , "deptId" , "parentId",
"children",SysDept.class);

参考连接:https://www.zhihu.com/tardis/sogou/art/68094736

 

posted @ 2020-09-16 10:09  小尼  阅读(388)  评论(0编辑  收藏  举报