Parse json with json-path

    In our daily development, sometimes we need to get a value from a json string, or get some values ​​from a json string. If you first use Gson or Jackson to convert it into a java object to get the value, sometimes it is It is very troublesome, so is there a way to extract the data in json according to the expression, just like using the xpath syntax to manipulate the xml file, the answer is yes, jsonPath is such a simple tool for manipulating json in java.

   The URL of jsonPath on github is as follows: https://github.com/json-path/JsonPath

1. Operators in json-path

 

2. Functions that can be used in json-path

 

3. Filter operator

 4. Example of expression usage:

 1. Data preparation

{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

 2. Sample code



 5. Use in JAVA code

1. Introduce the dependency of json-path into the pom.xml file

<dependency>
	<groupId>com.jayway.jsonpath</groupId>
	<artifactId>json-path</artifactId>
	<version>2.4.0</version>
</dependency>

 2. Write code

package com.huan.json;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.spi.json.JsonProvider;

/**
 * Test the use of jsonpath
 *
 * @describe
 * @authorhuan
 *@time December 31, 2017 - 4:34:11 pm
 */
public class JsonPathTest {
	public static void main(String[] args) {
		String json = readJson();
		Configuration configuration = Configuration.defaultConfiguration();
		configuration = configuration.addOptions(//
				Option.DEFAULT_PATH_LEAF_TO_NULL, // if the path does not exist return null instead of throwing PathNotFoundException
				Option.SUPPRESS_EXCEPTIONS // Suppress the throwing of exceptions, return [] when Option.ALWAYS_RETURN_LIST is set, otherwise return null
		);
		// If there is gson in the project, you can create a new GsonJsonProvider here, then return the object
		// configuration.jsonProvider(new GsonJsonProvider());
		JsonProvider jsonProvider = configuration.jsonProvider();
		/**
		 * The json is pre-parsed here. By default, the JsonPath.read method will re-parse the json every time it is dropped. If it is pre-parsed here, there is no need to parse it every time.
		 */
		Object document = jsonProvider.parse(json);
		// 1. Get the author in all books
		List<String> authors = JsonPath.read(document, "$.store.book[*].author");
		System.out.println(authors);
		// 2. Get books whose price is greater than $.expensive
		List<Map<String, Object>> books = JsonPath.read(document, "$.store.book[?(@.price > $.expensive)]");
		System.out.println(books);
		// 3. Output an expression that does not exist, because there is a configuration for this option, all returned is Option.DEFAULT_PATH_LEAF_TO_NULL
		Object notExistsValue = JsonPath.using(configuration).parse(document).read("$.not-exists-path.path");
		System.out.println(notExistsValue);
		// 4. There are multi-level attribute missing
		Object object = JsonPath.using(configuration).parse(document).read("$.not-exists.path");
		System.out.println(object);
	}

	public static String readJson() {
		StringBuilder builder = new StringBuilder();
		try (InputStream is = JsonPathTest.class.getResourceAsStream("data.json"); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr);) {
			String line;
			while (null != (line = br.readLine())) {
				builder.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace ();
		}
		return builder.toString();
	}

}

 3. Results

 

6. Matters needing attention:

      1. In the filter of json-path, 1 and '1' are not equal.

      2. Strings in filter need to be enclosed in single or double quotes

      3. The JsonPath.read method will parse json every time. The solution is to parse json in advance

      4. Some enumeration values ​​are provided in Option to control the return of the parsing result

      5. If you don't want to use the default JsonProvider, you can provide one yourself.

 

7. For the complete mind map, see the attachment.
 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326480996&siteId=291194637