在Java中处理JSON数据时,org.json.JSONArray 是一个常用的类,它用于表示JSON数组。JSONArray 类允许你在程序中创建和操作JSON数组格式的数据。下面我将详细介绍JSONArray的一些基本用法,并给出相应的代码示例。
首先,确保你的项目中包含了 org.json 库。如果你没有这个库,可以通过Maven或者Gradle添加依赖来引入它。对于Maven,可以在 pom.xml 文件中添加如下依赖:
2
3
4
5
基本API
构造函数:
public JSONArray(): 创建一个新的空的JSONArray对象。public JSONArray(String source): 创建一个新的JSONArray,该数组的初始内容为source字符串表示的数组。
增加元素:
public JSONArray put(int index, Object value): 将值添加到指定索引位置。public int put(Object value): 向数组末尾添加一个值。
获取元素:
public Object get(int index): 获取指定索引处的对象。public boolean getBoolean(int index): 获取指定索引处的布尔值。public double getDouble(int index): 获取指定索引处的双精度浮点数。public int getInt(int index): 获取指定索引处的整数值。public String getString(int index): 获取指定索引处的字符串。public JSONObject getJSONObject(int index): 获取指定索引处的JSONObject。public JSONArray getJSONArray(int index): 获取指定索引处的JSONArray。
其他方法:
public int length(): 返回数组中的元素数量。public boolean isNull(int index): 检查指定索引处的值是否为null。public JSONArray optJSONArray(int index): 如果存在,则返回指定索引处的JSONArray;否则返回null。public JSONObject optJSONObject(int index): 如果存在,则返回指定索引处的JSONObject;否则返回null。public Object opt(int index): 如果存在,则返回指定索引处的对象;否则返回null。import org.json.JSONArray;
2import org.json.JSONObject;
3
4public class JsonArrayExample {
5 public static void main(String[] args) {
6 // 创建一个空的JSONArray对象
7 JSONArray jsonArray = new JSONArray();
8
9 // 添加元素
10 jsonArray.put("apple");
11 jsonArray.put(42);
12 jsonArray.put(new JSONObject().put("key", "value"));
13
14 // 打印整个JSONArray
15 System.out.println(jsonArray.toString());
16
17 // 获取元素
18 System.out.println("Element at index 0: " + jsonArray.getString(0));
19 System.out.println("Element at index 1: " + jsonArray.getInt(1));
20 System.out.println("Element at index 2: " + jsonArray.getJSONObject(2).toString());
21
22 // 添加另一个JSONArray
23 JSONArray subArray = new JSONArray().put("banana").put("orange");
24 jsonArray.put(subArray);
25
26 // 获取子数组并打印
27 System.out.println("Sub array at index 3: " + jsonArray.getJSONArray(3).toString());
28 }
29}