使用com.jayway.jsonpath.JsonPath包进行JSON的快速解析、设置值需要注意的性能提升方法

一、包地址

  1、Maven:http://mvnrepository.com/artifact/com.jayway.jsonpath/json-path

<!-- https://mvnrepository.com/artifact/com.jayway.jsonpath/json-path -->
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.4.0</version>
</dependency>

  2、Github:https://github.com/json-path/JsonPath

二、用法

  1、取路径 

Configuration conf = Configuration.builder()
   .options(Option.AS_PATH_LIST).build();

List<String> pathList = using(conf).parse(json).read("$..author");

assertThat(pathList).containsExactly(
    "$['store']['book'][0]['author']",
    "$['store']['book'][1]['author']",
    "$['store']['book'][2]['author']",
    "$['store']['book'][3]['author']");

  2、取值

String json = "...";
Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);

String author0 = JsonPath.read(document, "$.store.book[0].author");
String author1 = JsonPath.read(document, "$.store.book[1].author");

三、常用配置

    private void LoadJsonPathConfig() {
        this.jsonPathAsPathConfig = Configuration.builder().options(Option.AS_PATH_LIST, Option.ALWAYS_RETURN_LIST, Option.SUPPRESS_EXCEPTIONS, Option.DEFAULT_PATH_LEAF_TO_NULL).build();
        this.jsonPathAsValueConfig = Configuration.builder().options(Option.ALWAYS_RETURN_LIST, Option.SUPPRESS_EXCEPTIONS, Option.DEFAULT_PATH_LEAF_TO_NULL).build();
    }

以上两种配置,分别用于取路径和取值。

四、性能提示

1、读值或路径时,read方法,在调用时需要传入一个字符串的JSON内容,其实这种方法内部他会先编译表达式为JSONPATH对象,然后再存于内存之中。下次Read到相同表达式时,就直接取这个对象。所以,如果规则是固定不变的,可以在程序刚启动时,进行规则的预编译来提升性能。

JsonPath.read(document, "$.store.book[0].author");

编译方法参考:

JsonPath path=JsonPath.compile("$.store.book[0].author");

2、配置的构建是比较费时的,因此建议在程序启动时,进行预配置。常用配置无非下面两种:

    private void LoadJsonPathConfig() {
        this.jsonPathAsPathConfig = Configuration.builder().options(Option.AS_PATH_LIST, Option.ALWAYS_RETURN_LIST, Option.SUPPRESS_EXCEPTIONS, Option.DEFAULT_PATH_LEAF_TO_NULL).build();
        this.jsonPathAsValueConfig = Configuration.builder().options(Option.ALWAYS_RETURN_LIST, Option.SUPPRESS_EXCEPTIONS, Option.DEFAULT_PATH_LEAF_TO_NULL).build();
    }

五、测试地址

  模拟表达式测试地址:http://jsonpath.herokuapp.com

 

猜你喜欢

转载自www.cnblogs.com/songxingzhu/p/8950003.html