我一直在尝试使用 JSONPath 过滤 JSON 中的特定元素,然后仅选择返回的结果数组中的第一个项目。
我的 baisc JSONPath 看起来像这样:
$.store.book[?(@.category==fiction)].price
我想加这个
[0]
像这样过滤:$.store.book[?(@.category==fiction)][0].price
但它不返回结果或者如果我把
[0]
在最后一个“价格”之后,我收到此错误:Filter: [0]['price'] can only be applied to arrays
我一直在搜索,但找不到正确的语法来在应用过滤器后提取数组中的第一个元素,就像在 xpath 中一样。
这是我正在处理的基本 JSON:
{ "store": {
"book": [
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{ "category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{ "category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
最佳答案
目前唯一的解决办法是:
List<Double> prices = JsonPath
.parse(json)
.read("$.store.book[?(@.category == 'fiction')].price");
Double firstPrice = prices.isEmpty() ? null : prices.get(0);
关于json - 从 JSONPath 中的过滤器表达式中选择第 N 个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30322086/