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

如何生成无外层对象包装的JSON数组 移除外层数组名key

问题原因

你当前使用的JsonUtil.toJson()方法在序列化数组/集合类型参数时,默认添加了外层的{"values": []}包装结构,才会出现不符合预期的输出。

解决方案

方案1:使用JSON序列化库直接序列化List(推荐)

直接通过Gson/FastJSON/Jackson等常用序列化库序列化List<File>,无需手动构造JSONArray,代码更简洁:

// 1. 构造File集合
List<File> fileList = new ArrayList<>();
// 可添加多个File对象
fileList.add(new File(getFileName(base64), MimeTypes.ContentType(FileExtension.getType(base64)), folder, convertUriToBase64(), null));
// 2. 用Gson直接序列化集合,得到纯数组JSON
Gson gson = new Gson();
String targetJson = gson.toJson(fileList);
Log.d(TAG, targetJson);

方案2:直接调用JSONArray原生toString方法

如果你坚持使用org.json.JSONArray,直接调用其自带的toString()方法即可,不要通过JsonUtil.toJson()处理:

JSONArray jsonArray = new JSONArray();
jsonArray.put(new File(getFileName(base64), MimeTypes.ContentType(FileExtension.getType(base64)), folder, convertUriToBase64(), null));
// 直接调用原生toString方法输出纯数组结构
String targetJson = jsonArray.toString();
Log.d(TAG, targetJson);

注意:使用org.json.JSONArray直接存放自定义类对象时,只有类的public修饰的字段会被序列化,若你的File类字段需要保留包级访问权限,推荐使用方案1。

内容的提问来源于stack exchange,提问作者Tihan-Nico Paxton

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 03:54:03