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

Java使用Gson将嵌套List转换为指定结构JSON的错误排查

错误原因
  • 你把JsonObject main的初始化放在了外层循环外面,Java中对象是引用传递,你每次内层循环修改的都是同一个main对象实例,往main2里添加的也只是这个对象的引用,不是独立拷贝。所以下一轮循环修改main的属性时,之前已经添加到main2里的所有main引用对应的内容都会被同步修改,就出现了重复键、数据覆盖错乱的问题。
  • 你把gson.toJson(main2, writer)放在了循环内部,每处理一行国家数据就输出一次当前的main2,会导致最终输出多段不完整的JSON片段,而不是合法的完整JSON对象。
修正后实现代码
JsonObject main2 = new JsonObject();
// 提前提取表头,避免循环内重复获取
List<String> headers = table.get(0);

for (int row = 1; row < table.size(); row++) {
    // 每次处理新国家时新建独立的子JsonObject,避免引用复用
    JsonObject countryObj = new JsonObject();
    List<String> currentRow = table.get(row);
    for (int column = 1; column < headers.size(); column++) {
        JsonObject valueWrap = new JsonObject();
        valueWrap.add("value", new JsonParser().parse(currentRow.get(column)));
        countryObj.add(headers.get(column), valueWrap);
    }
    main2.add(currentRow.get(0), countryObj);
}
// 所有数据处理完成后统一输出完整JSON
gson.toJson(main2, writer);

修正后每个国家对应独立的子JSON对象,不会出现引用复用导致的覆盖问题,统一输出也保证了JSON结构完全符合要求。

内容的提问来源于stack exchange,提问作者Cristian Plata

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 02:09:05