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

Java中如何将包含JSONObject的JSONArray转换为字符串?

实现方法

你完全可以将构造好的JSONArray转换为JSON格式字符串,并存入Java的String类型变量。

首先先修正你原有代码的笔误:实例化JSONObject时写的new JSONobject()存在大小写错误,类名正确写法是JSONObject(第二个字母O为大写),否则会触发编译报错。

转换直接调用JSONArray提供的toString()方法即可,不需要额外引入其他依赖,完整示例代码如下:

import org.json.JSONArray;
import org.json.JSONObject;

public class TestJson {
    public static void main(String[] args) {
        JSONArray array = new JSONArray();
        JSONObject json = new JSONObject();
        json.put("time","72");
        json.put("min","22");
        array.put(json);

        // 转换为紧凑格式的JSON字符串
        String result = array.toString();
        // 输出结果:[{"min":"22","time":"72"}]
        System.out.println(result);

        // 如果需要输出带缩进的易读格式,可以传入缩进空格数调用重载方法
        String formatResult = array.toString(2);
        /* 格式化后输出:
        [
          {
            "min": "22",
            "time": "72"
          }
        ]
        */
        System.out.println(formatResult);
    }
}

说明:JSON规范本身不要求键值对的排列顺序,所以序列化后输出的字符串中time和min的顺序可能和你put的顺序不一致,这属于正常情况,不会影响后续的JSON解析逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 07:09:18