java怎么拼一个json数组

Java拼接JSON数组可使用JSONArray和JSONObject类实现:1. 创建JSONArray对象存储数组;2. 使用put()方法添加元素;3. 可选创建JSONObject对象并添加到JSONArray中嵌套;4. 添加JSONObject对象到JSONArray;5. 使用toString()方法拼接JSON字符串。

如何使用 Java 拼接 JSON 数组

拼接 JSON 数组可以通过使用 Java 的 JSONArrayJSONObject 类来实现。

步骤:

1. 创建一个 JSONArray 对象

JSONArray 对象用于存储 JSON 数组。

import org.json.JSONArray;

JSONArray jsonArray = new JSONArray();

2. 添加元素到 JSONArray 对象

可以使用 put() 方法向 JSONArray 对象中添加元素。元素可以是任何 JSON 数据类型,如字符串、数字、布尔值或嵌套的 JSONArrayJSONObject 对象。

jsonArray.put("John");
jsonArray.put(123);
jsonArray.put(true);

3. 创建一个 JSONObject 对象(可选)

如果需要嵌套 JSON 数组,可以在 JSONArray 对象中添加一个 JSONObject 对象。

JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "John");
jsonObject.put("age", 123);

4. 将 JSONObject 对象添加到 JSONArray 对象

jsonArray.put(jsonObject);

5. 拼接 JSON 字符串

一旦 JSONArray 对象创建好,可以使用 toString() 方法将其拼接成 JSON 字符串。

String jsonString = jsonArray.toString();

示例代码:

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

public class Main {
  public static void main(String[] args) {
    JSONArray jsonArray = new JSONArray();

    jsonArray.put("John");
    jsonArray.put(123);
    jsonArray.

put(true); JSONObject jsonObject = new JSONObject(); jsonObject.put("name", "John"); jsonObject.put("age", 123); jsonArray.put(jsonObject); String jsonString = jsonArray.toString(); System.out.println(jsonString); } }

输出:

["John",123,true,{"name":"John","age":123}]