Java 进阶 & JSONPath 表达式的使用

一、JSONPath使用需要的包
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.4.0</version>
</dependency>
二、使用说明

1、JSONPath是xpath在json的应用
2、JSONPath 是参照xpath表达式来解析xml文档的方式,json数据结构通常是匿名的并且不一定需要有根元素。
3、JSONPath 用一个抽象的名字$来表示最外层对象
4、JSONPath 允许使用通配符 * 表示所以的子元素名和数组索引

三、JSONPath表达式语法

JSONPath 表达式可以使用.符号解析json:
.store.book[0].title 或者使用[]符号['store']['book'][0]['title']

四、测试实例

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,
        "isbn": "0-553-21311-3"
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  }
}

首先,读取json文件,使用commons.io的 FileUtils的readFileToString方法:

String path =System.getProperty("user.dir")+File.separator+"testdata"+File.separator+"test.json";

String jsonString = FileUtils.readFileToString(new File(path),"utf-8");

ReadContext context = JsonPath.parse(json);

其次,输出book[1]的author值。有两种方法:
方法一:

JsonPath.read(json,"$.store.book[1].author");
或
context.read("$.store.book[1].author");
输出:Evelyn Waugh

方法二:

JsonPath.read(json,"$['store']['book'][1]['author']");
context.read("$['store']['book'][1]['author']");

输出:Evelyn Waugh

//输出book[*]中category == 'reference'的book

List<Object> categorys = context.read("$.store.book[?(@.category == 'reference')]");
for(Object st: categorys){
    System.out.println(st.toString());
}
输出:   {category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}

//输出book[*]中price>10的book

List<Object> prices = context.read("$.store.book[?(@.price>10)]");
for(Object p:prices){
    System.out.println(p.toString());
}
输出:{category=fiction, author=Evelyn Waugh, title=Sword of Honour, price=12.99, isbn=0-553-21311-3}

//bicycle[*]中含有color元素的bicycle

List<Object> color = context.read("$.store.bicycle[?(@.color)]");
for(Object is :color){
    System.out.println(is.toString());
}
输出://{color=red, price=19.95}

//输出该json中所有price的值

List<Object> pp = context.read("$..price");
for(Object p :pp){
    System.out.println(p.toString());
}
输出: 8.95  12.99   19.95

List<String> authors = context.read("$.store.book[*].author");
for (String str : authors) {
    System.out.println(str);
}
输出:Nigel Rees     Evelyn Waugh


更多请参考https://blog.csdn.net/qq_20641565/article/details/77162868

五、XPATH 和 JSONPath获取元素的方法比较

[]在xpath表达式总是从前面的路径来操作数组,索引是从1开始。
使用JOSNPath的[]操作符操作一个对象或者数组,索引是从0开始。


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容