加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – JsonPath:按数组中的值过滤

发布时间:2020-12-15 00:54:33 所属栏目:Java 来源:网络整理
导读:我正在尝试使用Jsonpath在我的Json中按值过滤数组.我想在下面的 JSON中获取该国家的long_name.为了做到这一点,我按类型[0] ==“country”过滤adress_components但它似乎不起作用. 我试过的JsonPath: $.results[0].address_components[?(@['types'][0]=="cou
我正在尝试使用Jsonpath在我的Json中按值过滤数组.我想在下面的 JSON中获取该国家的long_name.为了做到这一点,我按类型[0] ==“country”过滤adress_components但它似乎不起作用.

我试过的JsonPath:

$.results[0].address_components[?(@['types'][0]=="country")].long_name

我想要的结果是:“加拿大”.

JSON:

{
       "results" : [
          {
             "address_components" : [
                {
                   "long_name" : "5510-5520","short_name" : "5510-5520","types" : [ "street_number" ]
                },{
                   "long_name" : "Yonge Street","short_name" : "Yonge St","types" : [ "route" ]
                },{
                   "long_name" : "Willowdale","short_name" : "Willowdale","types" : [ "neighborhood","political" ]
                },{
                   "long_name" : "North York","short_name" : "North York","types" : [ "political","sublocality","sublocality_level_1" ]
                },{
                   "long_name" : "Toronto","short_name" : "Toronto","types" : [ "locality",{
                   "long_name" : "Toronto Division","short_name" : "Toronto Division","types" : [ "administrative_area_level_2",{
                   "long_name" : "Ontario","short_name" : "ON","types" : [ "administrative_area_level_1",{
                   "long_name" : "Canada","short_name" : "CA","types" : [ "country",{
                   "long_name" : "M2N 5S3","short_name" : "M2N 5S3","types" : [ "postal_code" ]
                }
             ]
            }
       ],"status" : "OK"
}

谢谢您的帮助.

解决方法

以下JSONPath将起作用:
$..address_components[?(@.types[0] == 'country')].long_name

打破它:

> $.. address_components:专注于address_components数组
> [?(@.types [0] ==’country’)]:找到address_components子文档,该文档具有名为“type”的类型属性,其中包含第一个值为“country”的数组
> .long_name:返回此子文档的long_name属性.

使用Jayway JsonPath Evaluator和Java验证:

JSONArray country = JsonPath.parse(json)
    .read("$..address_components[?(@.types[0] == 'country')].long_name");

// prints Canada
System.out.println(country.get(0));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读