这是笔者在工作中碰到的一个需求 需要对复杂的json进行格式校验 自己手动解析json效率低 而且容易出错 于是使用json schema进行json校验 效率高
springBoot版本2.7.3
pom添加如下依赖
<dependency> <groupId>com.github.fge</groupId> <artifactId>json-schema-validator</artifactId> <version>2.2.6</version> </dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> <version>3.0.4</version> </dependency>
自定义一个json文件 定义规则twinSchema.json 放于resources根目录下
{ "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "id": { "type": "string", "pattern": "^metastar:define:.*$" }, "type": { "type": "string", "enum": ["define"] }, "name": { "type": "string", "pattern": "^.*#.*$" } }, "required": ["id","type","name"] }
实际内容可以根据需要修改
解释:
parttern 字段表示 匹配 类似正则表达式 ^xxxx 表示以xxxx开头
enum 表示枚举 传入的type值只能为enum设置的值 此处为 define
required 表示 传入的json必须含有 id , type, name 字段 否则报错
随便写一个Controller测试
@RestController @RequestMapping("/test") public class TestJsonController { @PostMapping("/user") public String createUser(@RequestBody String json) throws ProcessingException, IOException { JsonNode schemaNode = JsonLoader.fromResource("/twinSchema.json"); JsonSchema schema = JsonSchemaFactory.byDefault().getJsonSchema(schemaNode); //解析用户提交的json数据 JsonNode userNode = JsonLoader.fromString(json); //校验json是否符合规则 ProcessingReport validate = schema.validate(userNode); if(validate.isSuccess()){ return "User is created successfully"; }else { return validate.toString(); } } }
postman测试1 数据正确
结果
postman测试2 数据错误
结果
博客为原创 如需转载或引用请注明出处