一、包地址
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