Java spring boot uses custom annotations to verify JSON schema

Time:2022-5-10

1、 First, there are two open source tools https://github.com/everit-org/json-schema and https://github.com/java-json-tools/json-schema-validator

Difference: in terms of performance, everit is completely rolled FGE, which is at least twice what the official said. In the actual test process, there is almost a gap of 20 times. Although FGE uses Jackson JSON, which may have a relatively low learning cost, it is found that the use of everit is not complicated. It should be noted that the package needs to be imported correctly (org. JSON). The only advantage of FGE is that the error information is more detailed. Another difference is that everit fails to verify by throwing an exception, while FGE returns a Boolean value.

2、 Spring boot custom annotation integration jsonschema

1. First of all, the constraintvalidator class is mainly used to verify that the attributes in the bean are used together with the @ valid or @ validated annotation. If this annotation is not added, your customized annotation will not take effect, which is very important.

2. Generally, the parameters in the controller method in the project are received by bean, so you can use constraintvalidator to verify whether the field properties are legal. Then, if the parameter passed in by the controller is a map object, we cannot use this method to verify whether the field is legal. At this time, we need to write a pile of if else judgments in the code, which increases the redundancy of the code.

3、 Without much to say, let’s go directly to the verification code case I wrote:

Step 1: create annotation class

    package com.example.demo.config;

    import java.lang.annotation.*;

    @Retention(RetentionPolicy.RUNTIME)

    @Documented

    @Target({ElementType.PARAMETER,ElementType.METHOD})

    public @interface JsonValid {

        String schemaName();

String message() default “JSON data verification failed”;

    }

Step 2: verify the rule facet class

    package com.example.demo.service;第二步:校验规则切面类    package com.example.demo.service;        import com.alibaba.fastjson.JSONObject;    import com.example.demo.config.JsonValid;    import org.aspectj.lang.JoinPoint;    import org.aspectj.lang.annotation.Aspect;    import org.aspectj.lang.annotation.Before;    import org.aspectj.lang.annotation.Pointcut;    import org.everit.json.schema.Schema;    import org.everit.json.schema.ValidationException;    import org.everit.json.schema.loader.SchemaLoader;    import org.json.JSONTokener;    import org.slf4j.Logger;    import org.slf4j.LoggerFactory;    import org.springframework.stereotype.Component;        import java.io.InputStream;            /**     * @author zhouxiang     * @describe     * @create 2021/10/20 14:47     * @since 1.0.0     */    @Component    @Aspect    public class JsonValidatedAop {            private final Logger logger = LoggerFactory.getLogger(JsonValidatedAop.class);            @Pointcut("@annotation(com.example.demo.config.JsonValid)")        private void pointcut() {        }            @Before("pointcut() && @annotation(jsonValid)")        public void before(JoinPoint joinPoint, JsonValid jsonValid) {            Object[] args = joinPoint.getArgs();            if(args != null) {                String jsonString = JSONObject.toJSONString(args[0]);                /** 验证的结果,可以返回,也可以写个全局捕捉的异常 */                String validMsg = validJson(jsonString, jsonValid.schemaName());            }            logger.info("数据:"+ JSONObject.toJSONString(args) + jsonValid.schemaName());        }            /**         * 使用开源工具https://github.com/java-json-tools/json-schema-validator校验json         *         * @param jsonString 被校验数据         * @param schemaName 校验schema名称         * @return 返回失败消息,为空则校验成功         */        public String validJson(String jsonString, String schemaName) {            StringBuilder sBuilder = new StringBuilder();            try {                //InputStream inputStream = getClass().getResourceAsStream("/schema/hello.json");                //org.json.JSONObject rawSchema = new org.json.JSONObject(new JSONTokener(inputStream));                org.json.JSONObject rawSchema = new org.json.JSONObject(jsonString);                InputStream in1 = getClass().getResourceAsStream("/schema/"+schemaName);                org.json.JSONObject sSchema = new org.json.JSONObject(new JSONTokener(in1));                Schema schema = SchemaLoader.load(sSchema);                schema.validate(rawSchema);            } catch (ValidationException e) {                logger.error(e.getMessage());                sBuilder.append(e.getMessage());            }            return sBuilder.toString();        }    }

    import com.alibaba.fastjson.JSONObject;

    import com.example.demo.config.JsonValid;

    import org.aspectj.lang.JoinPoint;

    import org.aspectj.lang.annotation.Aspect;

    import org.aspectj.lang.annotation.Before;

    import org.aspectj.lang.annotation.Pointcut;

    import org.everit.json.schema.Schema;

    import org.everit.json.schema.ValidationException;

    import org.everit.json.schema.loader.SchemaLoader;

    import org.json.JSONTokener;

    import org.slf4j.Logger;

    import org.slf4j.LoggerFactory;

    import org.springframework.stereotype.Component;

    import java.io.InputStream;

    /**

    * @author zhouxiang

    * @describe

    * @create 2021/10/20 14:47

    * @since 1.0.0

    */

    @Component

    @Aspect

    public class JsonValidatedAop {

        private final Logger logger = LoggerFactory.getLogger(JsonValidatedAop.class);

        @Pointcut(“@annotation(com.example.demo.config.JsonValid)”)

        private void pointcut() {

        }

        @Before(“pointcut() && @annotation(jsonValid)”)

        public void before(JoinPoint joinPoint, JsonValid jsonValid) {

            Object[] args = joinPoint.getArgs();

            if(args != null) {

                String jsonString = JSONObject.toJSONString(args[0]);

/**The verification result can be returned or an exception caught globally can be written*/

                String validMsg = validJson(jsonString, jsonValid.schemaName());

            }

logger. Info (“data:” + jsonobject. Tojsonstring (args) + jsonvalid schemaName());

        }

        /**

*Using open source tools https://github.com/java-json-tools/json-schema-validator Check JSON

        *

*@ param jsonstring verified data

*@ param schemaname verify schema name

*@ return returns a failure message. If it is empty, the verification is successful

        */

        public String validJson(String jsonString, String schemaName) {

            StringBuilder sBuilder = new StringBuilder();

            try {

                //InputStream inputStream = getClass().getResourceAsStream(“/schema/hello.json”);

                //org.json.JSONObject rawSchema = new org.json.JSONObject(new JSONTokener(inputStream));

                org.json.JSONObject rawSchema = new org.json.JSONObject(jsonString);

                InputStream in1 = getClass().getResourceAsStream(“/schema/”+schemaName);

                org.json.JSONObject sSchema = new org.json.JSONObject(new JSONTokener(in1));

                Schema schema = SchemaLoader.load(sSchema);

                schema.validate(rawSchema);

            } catch (ValidationException e) {

                logger.error(e.getMessage());

                sBuilder.append(e.getMessage());

            }

            return sBuilder.toString();

        }

    }

Step 3: controller class

    package com.example.demo.controller;

    import com.example.demo.config.JsonValid;

    import org.slf4j.Logger;

    import org.slf4j.LoggerFactory;

    import org.springframework.web.bind.annotation.PostMapping;

    import org.springframework.web.bind.annotation.RequestBody;

    import org.springframework.web.bind.annotation.RestController;

    import java.util.HashMap;

    import java.util.Map;

    /**

    * @author zhouxiang

    * @describe

    * @create 2021/8/23 11:08

    * @since 1.0.0

    */

    @RestController

    public class ValidatorController {

        private final Logger logger = LoggerFactory.getLogger(ValidatorController.class);

        @PostMapping(“/test1”)

        @JsonValid(schemaName = “s.json”)

        public Map<String, Object> test(@RequestBody Map<String,Object> map)

        {

logger. Info (“received data:” + map. Tostring());

            Map<String, Object> responseMap = new HashMap<>();

            responseMap.put(“ResponseStatusListObject”, “success”);

            return responseMap;

        }

    }

Step 4: test data

    url:http://ip:8083/demo/test1 POST

JSON data:

    {

      “rectangle” : {

        “a” : 6,

        “b” : “21”

      }

    }

The schema test file is placed in resources / schema / s.json:

    {

      “type” : “object”,

      “properties” : {

        “rectangle” : {“$ref” : “#/definitions/Rectangle” }

      },

      “definitions” : {

        “size” : {

          “type” : “number”,

          “minimum” : 0

        },

        “Rectangle” : {

          “type” : “object”,

          “properties” : {

            “a” : {“$ref” : “#/definitions/size”},

            “b” : {“$ref” : “#/definitions/size”}

          }

        }

      }

    }

Recommended Today

IOS audio mode avaudiosession

As a hardware resource, audio output is unique to IOS system. It is necessary to control each app through the system level global object “avaudiosession”. The control distance is as follows: 7GmDJTSBWag18Ae.png Common audio scenes Is it recording or playing? How to behave when the system mute key is pressed? Is the sound played from […]