如何将Java树形结构List转换为Fancytree所需JSON结构
解决方案:后端Java实现扁平部门数据转Fancytree树形JSON
核心思路
通过建立节点索引Map将扁平数据高效组装为树形结构,避免前端嵌套遍历的性能损耗,具体步骤:
- 用实体类映射Fancytree节点结构,保证类型安全和序列化效率
- 借助HashMap快速查找父节点,将时间复杂度从O(n²)降至O(n)
- 最后用JSON序列化工具输出目标格式
代码实现
1. Fancytree节点实体类
import java.util.ArrayList; import java.util.List; public class FancytreeNode { private String title; private String key; private boolean expanded = true; private boolean folder = true; private List<FancytreeNode> children = new ArrayList<>(); public FancytreeNode(String title, String key) { this.title = title; this.key = key; } // Getter & Setter public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public boolean isExpanded() { return expanded; } public void setExpanded(boolean expanded) { this.expanded = expanded; } public boolean isFolder() { return folder; } public void setFolder(boolean folder) { this.folder = folder; } public List<FancytreeNode> getChildren() { return children; } public void setChildren(List<FancytreeNode> children) { this.children = children; } }
2. 扁平数据转树形结构工具类
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class DeptTreeConverter { public static String convertToFancytreeJson(List<HashMap<String, String>> deptList) throws JsonProcessingException { // 建立节点索引:key=DEPT_IDX,value=对应Fancytree节点 Map<String, FancytreeNode> nodeMap = new HashMap<>(); List<FancytreeNode> rootNodes = new ArrayList<>(); // 第一步:遍历生成所有节点并加入索引 for (HashMap<String, String> dept : deptList) { String deptName = dept.get("DEPT_NAME"); String deptIdx = dept.get("DEPT_IDX"); FancytreeNode node = new FancytreeNode(deptName, deptIdx); nodeMap.put(deptIdx, node); } // 第二步:挂载子节点到父节点 for (HashMap<String, String> dept : deptList) { String deptIdx = dept.get("DEPT_IDX"); String parentIdx = dept.get("DEPT_R_IDX"); FancytreeNode currentNode = nodeMap.get(deptIdx); if ("0".equals(parentIdx)) { // 父节点ID为0,属于根节点 rootNodes.add(currentNode); } else { // 找到父节点并添加子节点 FancytreeNode parentNode = nodeMap.get(parentIdx); if (parentNode != null) { parentNode.getChildren().add(currentNode); } } } // 序列化为格式化后的JSON ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNodes); } }
3. 使用示例
// 假设DEPT_LIST是已加载的部门数据列表 String fancytreeJson = DeptTreeConverter.convertToFancytreeJson(DEPT_LIST); // 直接返回该JSON字符串给前端即可
性能优势说明
- 两次线性遍历,时间复杂度O(n),远优于前端嵌套遍历的O(n²),数据量越大性能提升越明显
- HashMap索引实现O(1)时间的父节点查找,避免重复遍历列表
- 实体类序列化比HashMap更高效,生成的JSON结构更规整,减少前端解析开销
内容的提问来源于stack exchange,提问作者EggFriedRice
相关产品推荐
相关产品推荐

