zoukankan      html  css  js  c++  java
  • 使用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

     

  • 相关阅读:
    poj2392 Space Elevator(多重背包问题)
    poj1703 Find them, Catch them(并查集的应用)
    HDU 1867 A + B for you again(KMP算法的应用)
    HDU 1358 Period(kmp简单解决)
    nyoj 460 项链 (区间dp)
    Python内置函数(9)——callable--转载
    Python的hasattr() getattr() setattr() 函数使用方法详解--转载
    python assert 断言详细用法格式
    sam文件格式
    Linux中重定向--转载
  • 原文地址:https://www.cnblogs.com/songxingzhu/p/8950003.html
Copyright © 2011-2022 走看看