gpt4 book ai didi

java - 如何使用 JsonPath 执行子过滤器?

转载 作者:行者123 更新时间:2023-11-29 04:30:23 24 4
gpt4 key购买 nike

我已经 read the documentation ,而且我不知道如何使用 JsonPath 执行子过滤器。这是一个例子...

给定以下 JSON,我如何检索地址在 Sydney 的人员列表?

我已经尝试了 $.people[?(@.addresses[*].city=="Sydney")] 的变体,但无济于事。例如

  • $.people[?(@.addresses[*].city=="Sydney")]
  • $.people[?(@.addresses.city=="Sydney")]
  • $.people[?(@..city=="Sydney")]

JSON

{
"people": [{
"name": "George",
"addresses": [{
"city": "Sydney"
}]
},
{
"name": "Jane",
"addresses": [{
"city": "Brisbane"
}]
},
{
"name": "Fred",
"addresses": [{
"city": "Perth"
},
{
"city": "Sydney"
}
]
}
]
}

首选输出

{
"people": [{
"name": "George",
"addresses": [{
"city": "Sydney"
}]
},
{
"name": "Fred",
"addresses": [{
"city": "Perth"
},
{
"city": "Sydney"
}
]
}
]
}

我正在使用以下 Java 库:com.jayway.jsonpath:json-path:2.2.0

我正在使用 http://jsonpath.com/在浏览器中测试我的 jsonpath(也许这就是问题所在?)。

最佳答案

问题是 @.addresses[*].city 是一个集合。它不是这个人的任何城市,也不是这个人的唯一(每个)城市。

如果您正在寻找在悉尼有一些地址的人,查询应该是:

"$.people[?(\"Sydney\"in @.addresses[*].city)]"

例子:

String filter = "$.people[?(\"Sydney\" in @.addresses[*].city)]";
ReadContext ctx = JsonPath.parse(json);
List<Map<String, Object>> rez = ctx.read(filter, List.class);

如果您正在寻找所有地址都在悉尼的人,我不知道正确的查询。可以使用 Predicate,但代码非常复杂。

仅供引用:

List<Map<String, Object>> rez = JsonPath.parse(json).read(
"$.people[?]",
List.class,
new Predicate() {
@Override
public boolean apply(PredicateContext ctx) {
Map<String, Object> map = ctx.item(Map.class);
ReadContext readContext = JsonPath.parse(JSONObject.toJSONString(map));
List<String> allAddresses = readContext.read("$.addresses[*].city");
List<String> sydneyAddresses = readContext.read("$.addresses[?(@.city=='Sydney')].city");
return allAddresses.size() == sydneyAddresses.size();
}
});

关于java - 如何使用 JsonPath 执行子过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43994824/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com