Java 将多个 JSONObject 转换为 JSONArray
可以使用 JSONArray 的构造方法,将多个 JSONObject 对象转换成 JSONArray 对象。
示例代码如下:
import org.json.JSONArray;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
JSONObject obj1 = new JSONObject();
obj1.put('name', 'Alice');
obj1.put('age', 20);
JSONObject obj2 = new JSONObject();
obj2.put('name', 'Bob');
obj2.put('age', 25);
JSONArray jsonArray = new JSONArray();
jsonArray.put(obj1);
jsonArray.put(obj2);
System.out.println(jsonArray);
}
}
运行以上代码,输出结果为:
[{"age":20,"name":"Alice"},{"age":25,"name":"Bob"}]
可以看到,多个 JSONObject 对象已经成功转换成 JSONArray 对象。
原文地址: https://www.cveoy.top/t/topic/oCHo 著作权归作者所有。请勿转载和采集!