You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于公司父子ID原始数据构建层级JSON的Java实现咨询

扁平化公司关联数据转嵌套JSON Java实现方案

实现思路

  • 定义公司节点实体,存储公司ID和子节点列表
  • 用Map缓存所有公司ID对应的节点对象,避免重复遍历查找
  • 一次遍历完成父子关系组装,同时筛选出根节点
  • 序列化根节点列表得到目标嵌套JSON

代码实现

1. 节点实体类

import com.fasterxml.jackson.annotation.JsonInclude;
import java.util.List;

// 空child字段不参与序列化
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CompanyNode {
    private Integer id;
    private List<CompanyNode> child;

    public CompanyNode(Integer id) {
        this.id = id;
    }

    // getter、setter
    public Integer getId() { return id; }
    public void setId(Integer id) { this.id = id; }
    public List<CompanyNode> getChild() { return child; }
    public void setChild(List<CompanyNode> child) { this.child = child; }
}

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 CompanyTreeBuilder {
    public static void main(String[] args) throws JsonProcessingException {
        // 此处模拟原始数据,实际使用可替换为读取CSV/数据库的逻辑
        List<Map<String, Integer>> rawData = List.of(
                Map.of("CompanyId", 1, "ParentId", 1),
                Map.of("CompanyId", 2, "ParentId", 1),
                Map.of("CompanyId", 3, "ParentId", 1),
                Map.of("CompanyId", 4, "ParentId", 2),
                Map.of("CompanyId", 5, "ParentId", 2)
        );

        // 缓存所有公司节点
        Map<Integer, CompanyNode> idToNodeMap = new HashMap<>();
        for (Map<String, Integer> row : rawData) {
            Integer companyId = row.get("CompanyId");
            idToNodeMap.put(companyId, new CompanyNode(companyId));
        }

        // 组装父子关系、收集根节点
        List<CompanyNode> rootList = new ArrayList<>();
        for (Map<String, Integer> row : rawData) {
            Integer currentId = row.get("CompanyId");
            Integer parentId = row.get("ParentId");
            CompanyNode currentNode = idToNodeMap.get(currentId);

            // 根节点判断规则:当前ID等于父ID,可按需调整
            if (currentId.equals(parentId)) {
                rootList.add(currentNode);
                continue;
            }

            // 挂载到父节点下
            CompanyNode parentNode = idToNodeMap.get(parentId);
            if (parentNode != null) {
                if (parentNode.getChild() == null) {
                    parentNode.setChild(new ArrayList<>());
                }
                parentNode.getChild().add(currentNode);
            }
        }

        // 输出格式化JSON
        ObjectMapper mapper = new ObjectMapper();
        String result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootList);
        System.out.println(result);
    }
}

3. JSON序列化依赖(Maven)

如果使用Jackson做JSON序列化,可在pom.xml中添加如下依赖:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version>
</dependency>

注意事项

  • 上述代码根节点判断规则为「公司ID等于父ID」,如果业务中根节点规则为「无对应父节点记录」,调整判断条件即可
  • 若原始数据存在无效父ID,可自行添加异常处理逻辑
  • 如需子节点按指定规则排序,可在挂载到父节点时对子列表做排序处理

内容的提问来源于stack exchange,提问作者Sandip Jangra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 14:39:00