使用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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM