1. JSONPath
- 官方文档
https://github.com/alibaba/fastjson/wiki/JSONPath
1.1 基础知识
-
$
表示根
- 语法:
$.element
(注:路径表达式区分大小写)
- 嵌套查询
$.parentElement.element
2. JSONPath 示例
@Test
public void demo() {
OrderDTO orderDTO = new OrderDTO("1001", "20230101001", 0);
// 不加 $ 也行,等价 $.orderCode
JSONPath compile = JSONPath.compile("orderCode");
System.out.println(compile.eval(orderDTO));
}
3. 获取属性值
@Test
public void pathValue() {
OrderDTO orderDTO = new OrderDTO("1001", "20230101001", 0);
String extendCondition = "fields=orderCode, orderStatus, tradeId;";
// 解析
Map<String, String> params = new HashMap<>();
if (extendCondition.trim().contains(";")) {
String[] conditionArray = extendCondition.trim().split(";");
for (String item : conditionArray) {
if (StringUtils.isNotEmpty(item) && item.contains("=")) {
params.put(item.split("=")[0].trim(), item.split("=")[1].trim());
}
}
}
String orderFields = Optional.ofNullable(params.get("fields"))
.filter(StringUtils::isNotEmpty)
.orElse("$.orderCode, $.orderStatus, $.tradeId");
List<JSONPath> jsonPaths = Splitter.on(",").trimResults().omitEmptyStrings()
.splitToList(orderFields)
.stream()
.map(JSONPath::compile)
.collect(Collectors.toList());
String orderInfo = Joiner.on(",").skipNulls().join(jsonPaths.stream()
.map(jsonPath -> jsonPath.eval(orderDTO))
.map(obj -> {
if (obj instanceof String) {
return (String)obj;
} else {
return String.valueOf(obj);
}
})
.collect(Collectors.toList()));
System.out.println(orderInfo);
}
网友评论