1. 路径表达式
- XML 的 XPath,示例
/cities/city[1]/id
- JSON 的 JSONPath
2. JSONPath
概念:JSONPath 是查询 JSON 对象的元素的标准化方式。JSONPath 使用表达式在 JSON 文档中的元素、嵌套元素和数组之间导航
语法:$.elementName
(注:路径表达式区分大小写)
查询嵌套的元素 $.parentElement.element
JSONPath | desc |
---|---|
$ | 根元素 |
* | 通配符 |
[num] | 根据下标访问数组元素 |
[num0,num1,num2…] | 访问多个数组元素 |
[start:end] | 数组范围访问 |
2.1 com.alibaba.fastjson.JSONPath
public class JSONPath implements JSONAware {
public static Object eval(Object rootObject, String path) {
JSONPath jsonpath = compile(path);
return jsonpath.eval(rootObject);
}
}
示例:
User user = new User("tinyspot", 20, 2000);
// 方式一:
Object eval = JSONPath.eval(user,"$.name");
System.out.println(String.valueOf(eval));
// 若指定的元素不存在或无值,返回 null
Object other = JSONPath.eval(user,"$.other");
// 方式二:参看 eval(Object rootObject, String path) 实现方式
JSONPath jsonPath = JSONPath.compile("$.name");
Object eval1 = jsonPath.eval(user);
System.out.println(eval1);
获取根元素 JSONPath.eval(user, "$");
获取所有属性
Object eval = JSONPath.eval(user, "$.*");
// java.util.ArrayList
System.out.println(eval.getClass().getTypeName());
2.2 eval() 使用
User user = new User("tinyspot", 20, 2000);
String str = "$.name, $.age, $.salary";
List<String> strings = Splitter.on(",").trimResults().omitEmptyStrings().splitToList(str);
List<String> collect = strings.stream()
.map(path -> JSONPath.eval(user, path))
.map(String::valueOf)
.collect(Collectors.toList());
String join = Joiner.on(",").skipNulls().join(collect);
System.out.println(join);
List<JSONPath> paths = strings.stream().map(JSONPath::compile).collect(Collectors.toList());
List<String> infos = paths.stream()
.map(jsonPath -> jsonPath.eval(user))
.map(String::valueOf).collect(Collectors.toList());
2.3 解析数组里的元素
List<User> users = Arrays.asList(new User("tinyspot", 20, 2000),
new User("Echo", 25, 2500),
new User("Try", 30, 3000));
JSONArray names = (JSONArray) JSONPath.eval(users, "$.name");
Object userArray = JSONPath.eval(users, "[1,2]");
Object userArray2 = JSONPath.eval(users, "[1:2]");
References
- FastJson - JSONPath 使用
网友评论