JSONPATH json parsing tool

Keywords: Programming JSON Java github less

1. jsonPath's address on github is as follows: https://github.com/json-path/JsonPath

2. json-path Quick Start

Operators in json-path

2. Functions available in json-path

3. Filter operators

 

 

3. maven dependence

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

 

4. util code

package com.ysma.ppt.util.resource;

import com.jayway.jsonpath.*;
import com.jayway.jsonpath.spi.json.JsonSmartJsonProvider;
import com.ysma.ppt.intf.pojo.TemplateDO;
import org.springframework.cglib.beans.BeanMap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ysma 2019-09-25
 * JsonPath Tool class
 * JsonPath The expression can be expressed in point notation: $. store. book [0].
 *                  Or parentheses: $['store']['book'][0]['title']
 *
 * real_param_response Table path field storage format, such as store.book[1].isbn
 */
public class JsonPathUtil {

    //The "root member object" in JsonPath is always called $, whether it's an object or an array.
    private static final String ROOT_PREFIX = "$";

    private static Configuration configuration;

    static {
        configuration = Configuration.builder().options(
                Option.DEFAULT_PATH_LEAF_TO_NULL, // If the path does not exist, return null instead of throwing PathNotFoundException
                Option.SUPPRESS_EXCEPTIONS // Suppress exception throwing, return [], or null when Option.ALWAYS_RETURN_LIST is set
        ).jsonProvider(new JsonSmartJsonProvider()).build();
    }

    /**
     * Analytic class
     * @param resJsonStr Back-reference object to be parsed
     * @param expectList Defined expected result set
     * @return Result set
     */
    public static Map<String, Object> parseJson(String resJsonStr, List<BeanMap> expectList){
        /*1.json is pre-parsed here. By default, the JsonPath.read method resolves json every time it is dropped. If it is pre-parsed here, it does not need to be parsed every time.*/
        DocumentContext context = JsonPath.parse(resJsonStr, configuration);

        //2. Constructing Return Results
        Map<String, Object> resultMap = new HashMap<>();

        expectList.forEach(beanMap -> {
            String path = String.join(".", ROOT_PREFIX, (String)beanMap.get("path"));

            //beanMap.get("dataType") data types are weakened
            Object val = context.read(path);
            resultMap.put((String)beanMap.get("code"), val);
        });

        return resultMap;
    }

    /**groovy This custom development can be used in scripts*/
    public static Map<String, Object> parsePathJson(String resJsonStr, List<Map<String, String>> pathList){
        /*1.json is pre-parsed here. By default, the JsonPath.read method resolves json every time it is dropped. If it is pre-parsed here, it does not need to be parsed every time.*/
        DocumentContext context = JsonPath.parse(resJsonStr, configuration);

        //2. Constructing Return Results
        Map<String, Object> resultMap = new HashMap<>();

        pathList.forEach(pathMap -> {
            String path = String.join(".", ROOT_PREFIX, pathMap.get("path"));

            //beanMap.get("dataType") data types are weakened
            Object val = context.read(path);
            resultMap.put(pathMap.get("code"), val);
        });

        return resultMap;
    }

    /**
     * https://www.baeldung.com/guide-to-jayway-jsonpath
     * Official address, query filter definition function, etc.
     */
    private static void testParse(String resJsonStr, List<BeanMap> expectList){
        Object obj = configuration.jsonProvider().parse(resJsonStr);

        expectList.forEach(beanMap -> {
            String path = String.join(".", ROOT_PREFIX, (String)beanMap.get("path"));
            Object read = JsonPath.read(obj, path, Filter.filter(Criteria.where("price").lt(5.5)));
            System.out.println("read:"+read);
        });
    }

    public static void main(String[] args) {
        List<TemplateDO> responseDOS = new ArrayList<>();
        TemplateDO rd = new TemplateDO();
        rd.setCode("color");
        rd.setPath("store.bicycle[?]");
        rd.setDataType("double");
        responseDOS.add(rd);

        /*ParamResponseRealDO rd2 = new ParamResponseRealDO();
        rd2.setCode("category");
        rd2.setPath("hehe.store.book[*].category");
        rd2.setDataType("array");
        responseDOS.add(rd2);*/

        List<BeanMap> expectList = responseDOS.stream().map(BeanMap::create).collect(Collectors.toList());

        String respJson = getRespJson();

        /*Map<String, Object> resultMap = parseJson(respJson, expectList);
        System.out.println(JSON.toJSONString(resultMap));*/

        testParse(respJson, expectList);
    }

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

@Data
public class TemplateDO{

    private String code;

    private String path;

    private String dataType;

}

 

5. The specific rules for the use of filters are explained on the official website, which provides great freedom and help for specific research and development.

For example, the use of Criteria in the testParse method is based on store.bicycle [?] semantics. One step more, one step less.

 

The content of the official website is less written because it is more stable. Huang_1993's blog copies more, because even one day he "retired to the mountains".

This is it!

 

Reference resources:

https://blog.csdn.net/fu_huo_1993/article/details/88350147 Given jsonpath's address and api sketch, very good

https://www.baeldung.com/guide-to-jayway-jsonpath The corresponding definition in the official website is given.

Posted by joecooper on Sat, 12 Oct 2019 07:07:57 -0700