跳到主要内容

深层路径详解

← 返回文档导航


深层路径是 JSONMap 的核心特性,用一个字符串表达式直接访问嵌套数据,无需逐层判空和强转。

// 传统方式:每层判空 + 强转
String city = null;
if (data != null && data.get("user") != null) {
Map user = (Map) data.get("user");
if (user.get("profile") != null) {
Map profile = (Map) user.get("profile");
if (profile.get("addresses") != null) {
List addresses = (List) profile.get("addresses");
if (!addresses.isEmpty()) {
Map addr = (Map) addresses.get(0);
city = (String) addr.get("city");
}
}
}
}

// JSONMap:1 行
String city = data.getStr("user.profile.addresses[0].city");

路径语法

语法说明示例
.对象属性user.name
[n]数组索引 n(从 0 开始)users[0]
[-n]倒数第 n 个users[-1]
混合任意组合users[0].profile.tags[-1]

点号访问

JSONMap data = new JSONMap("{\"user\":{\"name\":\"张三\",\"age\":25}}");

data.getStr("user.name"); // 张三
data.getInt("user.age"); // 25

数组索引

JSONMap data = new JSONMap("{\"tags\":[\"a\",\"b\",\"c\"]}");

data.getStr("tags[0]"); // a
data.getStr("tags[1]"); // b
data.getStr("tags[-1]"); // c(最后一个)
data.getStr("tags[-2]"); // b(倒数第二个)

混合路径

String json = "{" +
"\"users\":[" +
"{\"name\":\"张三\",\"profile\":{\"city\":\"北京\",\"tags\":[\"vip\",\"active\"]}}," +
"{\"name\":\"李四\",\"profile\":{\"city\":\"上海\",\"tags\":[\"normal\"]}}" +
"]" +
"}";

JSONMap data = new JSONMap(json);

data.getStr("users[0].name"); // 张三
data.getStr("users[0].profile.city"); // 北京
data.getStr("users[0].profile.tags[0]"); // vip
data.getStr("users[-1].profile.tags[-1]"); // normal

多维数组

JSONMap json = new JSONMap();
json.set("matrix[0][0]", 1);
json.set("matrix[0][1]", 2);
json.set("matrix[1][0]", 3);
json.set("matrix[1][1]", 4);
// → {"matrix":[[1,2],[3,4]]}

json.getInt("matrix[0][1]"); // 2
json.getInt("matrix[1][0]"); // 3

安全行为

路径中任意一环为 null,返回 null,不抛异常:

JSONMap data = new JSONMap("{\"user\":{\"name\":\"张三\"}}");

data.getStr("user.age"); // null(age 不存在)
data.getStr("user.profile.city"); // null(profile 不存在)
data.getStr("admin.name"); // null(admin 不存在)
data.getStr("tags[10]"); // null(数组越界)
data.getStr("tags[-10]"); // null(负索引越界)

// 类型不匹配也返回 null
data.getMap("user.name"); // null(name 是字符串,不是对象)

put vs set

// put:key 不解析,直接作为键名
json.put("a.b", 1);
// → {"a.b": 1}

// set:key 解析为路径
json.set("a.b", 1);
// → {"a": {"b": 1}}

最佳实践

// 1. 优先用路径表达式
String name = data.getStr("user.profile.name");

// 2. 提供默认值
String city = data.getStr("user.profile.city", "未知");

// 3. 用负索引获取最后元素
String lastTag = data.getStr("tags[-1]");

← 上一节:JSONList完整指南 | 返回文档导航 | 下一节:功能特性速查表 →