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

Java中List转JSONArray出现双层括号,如何生成单层JSON数组?

问题解决方法

问题原因

你当前用JSONUtil.putAll把整个COLUMN_NAMES列表作为单个元素存入了JSONArray,才导致出现双层嵌套的数组结构。

解决方案

直接遍历COLUMN_NAMES列表,将每个字符串元素逐个添加到JSONArray中,或者使用支持直接将List转为单层JSONArray的构造/转换方法。

示例代码(通用写法)

// 初始化目标字符串列表
List<String> COLUMN_NAMES = Arrays.asList("String_1", "String_2", "String_3", "String_4");

// 创建空JSONArray并逐个添加元素
JSONArray jsonArray = new JSONArray();
for (String column : COLUMN_NAMES) {
    jsonArray.add(column);
}

// 组装最终的JSONObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("fields", jsonArray);

// 输出结果:{"fields":["String_1","String_2","String_3","String_4"]}
System.out.println(jsonObject.toString());

简化写法(工具类支持时)

如果使用的JSON工具类支持直接用List初始化单层JSONArray,可直接用以下写法:

List<String> COLUMN_NAMES = Arrays.asList("String_1", "String_2", "String_3", "String_4");
JSONArray jsonArray = new JSONArray(COLUMN_NAMES);
JSONObject jsonObject = new JSONObject();
jsonObject.put("fields", jsonArray);

这样就能得到你期望的单层数组结构的JSON结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 23:15:56