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

如何将LinkedHashMap<String, List<Node>>转换为指定结构的JSONObject?

解决LinkedHashMap转指定JSON结构的问题

嘿,我来帮你搞定这个JSONObject转换的问题!你要的JSON结构是每个Map键对应一个嵌套数组,里面包着带items字段的对象,而items又是Node的集合。之前遇到覆盖问题,大概率是循环时复用了同一个JSON对象/数组,没每次都新建实例导致的。下面是具体的实现方案:

核心思路

  1. 初始化一个顶层JSONObject来存放最终结果
  2. 遍历你的LinkedHashMap的每个键值对
  3. 对每个键:
    • 创建外层的JSONArray(对应[{"items": ...}]这个结构)
    • 创建一个包裹items的JSONObject
    • 将List<Node>逐个转换成JSONObject,存入items对应的JSONArray
    • 把这些嵌套结构依次组装,最后放到顶层JSON的对应键下

完整代码示例

首先,假设你的Node类是这样的(需要提供getter方法,方便JSONObject读取属性):

class Node {
    private String value;
    private String label;

    public Node(String value, String label) {
        this.value = value;
        this.label = label;
    }

    // 必须的getter方法
    public String getValue() {
        return value;
    }

    public String getLabel() {
        return label;
    }
}

然后是转换逻辑的代码:

import org.json.JSONArray;
import org.json.JSONObject;
import java.util.LinkedHashMap;
import java.util.List;

public class MapToJsonConverter {
    public static void main(String[] args) {
        // 构建测试用的LinkedHashMap
        LinkedHashMap<String, List<Node>> dataMap = new LinkedHashMap<>();
        dataMap.put("element_one", List.of(new Node("1", "Donald"), new Node("2", "Goofy")));
        dataMap.put("element_two", List.of(new Node("1", "Peter"), new Node("2", "Wendy")));

        // 顶层JSON对象,用来存储最终结果
        JSONObject finalJson = new JSONObject();

        // 遍历Map中的每个键值对
        for (String key : dataMap.keySet()) {
            List<Node> nodeList = dataMap.get(key);

            // 1. 创建外层数组:对应每个key下的[{"items": ...}]
            JSONArray outerArray = new JSONArray();
            // 2. 创建包裹items的对象
            JSONObject itemsContainer = new JSONObject();
            // 3. 创建items对应的数组,用来存放Node转成的JSON对象
            JSONArray itemsArray = new JSONArray();

            // 遍历Node列表,逐个转成JSON对象
            for (Node node : nodeList) {
                JSONObject nodeJson = new JSONObject();
                nodeJson.put("value", node.getValue());
                nodeJson.put("label", node.getLabel());
                itemsArray.put(nodeJson);
            }

            // 组装嵌套结构
            itemsContainer.put("items", itemsArray);
            outerArray.put(itemsContainer);
            // 将组装好的结构放到顶层JSON的对应key下
            finalJson.put(key, outerArray);
        }

        // 输出格式化后的JSON(4是缩进空格数,方便阅读)
        System.out.println(finalJson.toString(4));
    }
}

关键注意点

  • 不要复用JSON实例:每次处理Map的一个键时,都要新建outerArray、itemsContainer和itemsArray。如果把这些实例定义在循环外面,每次循环只修改内容,就会导致所有键都指向同一个对象,最终被最后一次循环的内容覆盖。
  • 确保Node的属性可被读取:org.json库的JSONObject默认会通过getter方法读取属性,所以一定要给value和label提供getter,或者把字段设为public(不推荐)。

运行这段代码后,你就能得到完全符合预期的JSON结构啦!

内容的提问来源于stack exchange,提问作者Simone Colnaghi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:33:30