问题描述
我正在尝试使用json-path从json字符串中提取值.我怀疑我的问题与获取具体信息有关谓词应用后,来自JSONPath数组结果的对象,但链接没有为我提供答案.我的jsonfile看起来像这样:
I am trying to extract a value from a json string using json-path.I suspected that my question is related to Get specific object from JSONPath array result after predicate is applied but the link didn't provide me with the answer. My jsonfile looks like this:
{
"success": true,
"errorKey": null,
"results": {
"payments": [
{
"name": "current",
"all": {
"revenue": 390.32,
"count": 1
}
},
{
"name": "sameYesterday",
"all": {
"revenue": 613.24,
"count": 4
}
},
{
"name": "yesterday",
"all": {
"revenue": 613.24,
"count": 3
}
}
]
}
}
我想获取昨天的付款计数.以下查询绝对有效,但是它依赖于json数组中元素的位置,该位置可以更改:
I want to get yesterday's payment count. Following query definitely works, but it relies on the position of elements within the json array, which can change:
ReadContext ctx = JsonPath.parse(content);
ctx.read("$.results.payments[2].all.count");
我正在尝试使用名称匹配:
I was trying to work with name matching:
ctx.read("$.results.payments[?(@.name=='yesterday')].all.count[0]")
我的问题是,这总是返回一个空数组. ctx.read("$.results.payments [?(@.name =='yesterday')].all.count"返回[3](从逻辑上来说),我认为从结果数组中获取第一个元素就足够了,但我的结果数组始终为空.我在做什么错了?
My problem is that this always returns an empty array. ctx.read("$.results.payments[?(@.name=='yesterday')].all.count" returns [3] (logically) and I assumed taking the first element from the result array would be sufficient, but my result array is always empty.What am I doing wrong?
推荐答案
count
属性本身不是JSON中的数组,因此count
上的数组表示法(例如count[0]
)不起作用.但是表达式$.results.payments[?(@.name == 'yesterday')].all.count
在求值时会返回一个Java列表,因此要获取第一个count
,我们只需从列表中获取第一个元素即可:
count
property itself is not an array in your JSON so array notation on count
such as count[0]
doesn't work. But the expression $.results.payments[?(@.name == 'yesterday')].all.count
when evaluated returns a Java list so to get the first count
we can just get the first element from the list:
List<Integer> yesterdayCounts = ctx.read("$.results.payments[?(@.name == 'yesterday')].all.count");
int firstCount = yesterdayCounts.get(0);
assertThat(firstCount).isEqualTo(3);
这篇关于查询后从jsonpath数组中提取单个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!