1. Package address
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
2. Usage
1. Take the path
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. Value
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");
3. Common configuration
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(); }
The above two configurations are used to get the path and get the value respectively.
4. Performance Tips
1. When reading a value or path, the read method needs to pass in the JSON content of a string when it is called. In fact, this method will first compile the expression into a JSONPATH object, and then store it in memory. The next time Read reaches the same expression, this object is taken directly. Therefore, if the rules are fixed, you can precompile the rules when the program is just started to improve performance.
JsonPath.read(document, "$.store.book[0].author");
Compilation method reference:
JsonPath path=JsonPath.compile("$.store.book[0].author");
2. The construction of the configuration is time-consuming, so it is recommended to pre-configure when the program starts. The common configuration is nothing more than the following two:
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(); }
5. Test address
Simulated expression test address: http://jsonpath.herokuapp.com