工具:树结构数据生成
图
项目开发的某些场景中,会使用到上下级结构的数据,来完成类似于组织架构这样的复杂问题,接口数据在响应时可能需要给出上下级数据结构,就需要这样的转换工具,将数据进行处理再进行响应

转换工具代码

这里基于的是fastjson和hutool工具,如果没有,也可使用相同的思想实现

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.*;

/**
 * 指挥调度树结构
 */
public class CommonTree {

    public static int count = 0;    // 总数
    public static List<String> hasParentUidList = new ArrayList<>(); //有正常上级的ID列表

    /**
     * list数据转树结构
     *
     * @param treeList    源数据
     * @param parentId    开始父键的值
     * @param idKey       id键名称
     * @param parentIdKey 父键名称
     * @param childName   子键名称
     * @param handleSet   set
     * @return JSONArray
     */
    public static JSONArray listToTreeMap(List<?> treeList, String parentId, String idKey, String parentIdKey, String childName, Set<String> handleSet) {
        JSONArray childMenu = new JSONArray();
        handleSet = handleSet == null ? new HashSet<>() : handleSet;

        if (!handleSet.contains(parentId)) {
            for (Object object : treeList) {
                JSONObject jsonMenu = JSONObject.parseObject(JSON.toJSONString(object));
                String menuId = jsonMenu.getString(idKey);
                String pid = jsonMenu.getString(parentIdKey);
                if (parentId.equals(pid)) {
                    ++count;

                    JSONArray array = listToTreeMap(treeList, menuId, idKey, parentIdKey, childName, handleSet);

                    // 没有下级的是否才有下级字段
                    if (array.size() > 0) {
                        jsonMenu.put(childName, array);
                    }

                    childMenu.add(jsonMenu);
                }
            }
        }
        handleSet.add(parentId);
        if (StrUtil.isNotBlank(parentId)) {
            hasParentUidList.add(parentId);
        }
        return childMenu;
    }

}

使用方式

JSONArray jsonArray = CommonTree.listToTreeMap(
        departments,
        null,
        "id",
        "parentIdStr",
        "child",
        new HashSet<>()
);

注意事项

  1. 使用parentId实现无限下级问题,规定最上级为null
  2. 一定要加所有上级ID集合字段,便于查询所有的下级数据,在添加时查询到上级进行该处理(MySQL需要加新表实现)
  3. 如果按级进行查询,一定要加是否存在下级下级数量字段,便于给接口调用者使用