JSONList 完整指南
JSONList 继承 ArrayList<Object>,提供负索引访问、类型安全访问、链式操作能力。
构造方式
// 空列表
JSONList list = new JSONList();
// JSON 字符串
JSONList list = new JSONList("[1, 2, 3]");
// 逗号分隔字符串(自动拆分)
JSONList list = new JSONList("苹果,香蕉,橙子");
// → ["苹果", "香蕉", "橙子"]
// 数组
JSONList list = new JSONList(new String[]{"a", "b", "c"});
// 集合
JSONList list = new JSONList(Arrays.asList(1, 2, 3));
// 带类型转换
JSONList list = new JSONList("1,2,3", Integer.class);
// → [1, 2, 3]
// 指定初始容量
JSONList list = new JSONList(100);
负索引访问
JSONList list = new JSONList("[10, 20, 30, 40, 50]");
list.getInt(0); // 10(第一个)
list.getInt(1); // 20
list.getInt(-1); // 50(最后一个)
list.getInt(-2); // 40(倒数第二个)
list.getInt(-5); // 10(倒数第五个)
类型安全访问
JSONList list = new JSONList("[{\"name\":\"张三\",\"age\":25}, {\"name\":\"李四\",\"age\":30}]");
// 获取子对象
JSONMap first = list.getMap(0);
String name = first.getStr("name"); // 张三
// 直接用路径
String lastName = list.getStr("[-1].name"); // 李四
链式操作
JSONList list = new JSONList()
.adds("元素1")
.adds("元素2")
.adds("元素3");
API 参考
读取方法
// 基本类型
String getStr(int index)
String getStr(int index, String defaultValue)
Integer getInt(int index)
Long getLong(int index)
Double getDouble(int index)
Float getFloat(int index)
BigDecimal getBigDecimal(int index)
Boolean getBoolean(int index)
Date getDate(int index)
// 复杂类型
JSONMap getMap(int index)
JSONList getList(int index)
<T> T getObj(int index, Class<T> clazz)
// 列表转换
<T> List<T> asList(Class<T> clazz)
写入方法
JSONList adds(Object obj) // 链式添加
注意事项
// 1. 负索引越界:抛 IndexOutOfBoundsException
list.getInt(-4); // list 只有 3 个元素时越界
// 2. 类型转换失败:返回 null,不抛异常
JSONList list = new JSONList("[\"abc\", \"def\"]");
Integer num = list.getInt(0); // null("abc" 不能转数字)
// 3. 空值处理
Integer val = list.getInt(1, 0); // 默认值