JsonSchema 整合SpringBoot
2020-12-13 本文已影响0人
圆企鹅i
JsonSchema
就是一个json格式的 校验规则 校验写的json是否在你的规定内
以后工作遇到的问题也会更新在上面
代码
https://github.com/opop32165455/zeroBeginning.git
依赖的包
<!--json-schema-->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>3.1.1</version>
</dependency>
</dependencies>
copy的工具类 校验json
package com.fromzero.zerobeginning.Utils;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.JsonLoader;
import com.github.fge.jsonschema.core.report.ProcessingMessage;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.util.Iterator;
/**
* @Desciption: 校验json数据是否符合schema约定的标准
* level: 错误级别(应该就是error)
* schema:引起故障的模式的所在位置的 URI
* instance:错误对象
* domain:验证域
* keyword:引起错误的约束key
* found:现在类型
* expected:期望类型
* @Auther: ZhangXueCheng4441
* @Date:2020/12/13/013 15:40
*/
@Slf4j
public class JsonValidateUtil{
private final static JsonSchemaFactoryfactory = JsonSchemaFactory.byDefault();
/**
* 校验JSON
* @param schema json模式数据(可以理解为校验模板)
* @param instance 需要验证Json数据
* @return
*/
public static ProcessingReportvalidatorJsonSchema(String schema, String instance) throws IOException{
ProcessingReport processingReport =null;
// JsonNode jsonSchema = JsonLoader.fromResource("/");
// JsonNode jsonData = JsonLoader.fromResource("/");
JsonNode jsonSchema = JsonLoader.fromString(schema);
JsonNode jsonData = JsonLoader.fromString(instance);
processingReport =factory.byDefault().getValidator().validateUnchecked(jsonSchema, jsonData);
boolean success = processingReport.isSuccess();
if (!success) {
Iterator<ProcessingMessage> iterator = processingReport.iterator();
while (iterator.hasNext()) {
log.error(String.valueOf(iterator.next()));
}
}
return processingReport;
}
}
copy的工具类 导入文件
更推进hutool
package com.fromzero.zerobeginning.Utils;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.JsonNodeReader;
import java.io.*;
/**
* @Desciption: 从/src/main/resources目录中读取json文件
* @Auther: ZhangXueCheng4441
* @Date:2020/12/13/013 15:38
*/
public class ReadJsonFile{
/**
* 读取Json文件为String json
*
* @param filePath filePath为文件的相对于resources的路径
* @return
*/
public static StringreadJsonFileAsString(String filePath) {
filePath = ReadJsonFile.class.getResource(filePath).getPath();
String jsonStr ="";
try {
File jsonFile =new File(filePath);
FileReader fileReader =new FileReader(jsonFile);
Reader reader =new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
int ch =0;
StringBuffer sb =new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 读取Json文件为JsonNode
*
* @param filePath filePath为文件的绝对路径
* @return
*/
public static JsonNodereadJsonFileAsJsonNode(String filePath) {
JsonNode instance =null;
try {
instance =new JsonNodeReader().fromReader(new FileReader(filePath));
} catch (IOException e) {
e.printStackTrace();
}
return instance;
}
}
测试方法
package com.fromzero.zerobeginning;
import com.fromzero.zerobeginning.Utils.ReadJsonFile;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static com.fromzero.zerobeginning.Utils.JsonValidateUtil.validatorJsonSchema;
@SpringBootTest(classes = JsonSchemaApplication.class)
@RunWith(SpringRunner.class)
public class JsonSchemaApplicationTests{
@Test
public void contextLoads() {
System.out.println("1");
}
@Test
public void testschema() throws Exception{
String data = ReadJsonFile.readJsonFileAsString("/json/testString.json");
String schema = ReadJsonFile.readJsonFileAsString("/json/testSchema.json");
ProcessingReport processingReport =validatorJsonSchema(schema, data);
boolean success = processingReport.isSuccess();
System.out.println(success);
}
}
测试controller
package com.fromzero.zerobeginning.controller;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import static com.fromzero.zerobeginning.Utils.JsonValidateUtil.validatorJsonSchema;
/**
* @Desciption:
* @Auther: ZhangXueCheng4441
* @Date:2020/12/13/013 16:03
*/
@RestController
@RequestMapping("/json")
public class JsonSchemaControllerextends ApiController{
//测试使用json/testJson.txt中的json
@PostMapping("/verifyJson")
public RverifyJsonByJsonSchema(@RequestBody String info) {
JSONObject jsonObject = JSONUtil.parseObj(info);
String json = jsonObject.getStr("json");
String jsonSchema = jsonObject.getStr("jsonSchema");
try {
ProcessingReport processingReport =validatorJsonSchema(jsonSchema, json);
boolean success = processingReport.isSuccess();
return success(success);
} catch (IOException e) {
logger.error("解析过程出现错误");
e.printStackTrace();
return failed("解析过程出现错误");
}
}
}
测试使用的json
{
"json": {
"checked": false,
"dimensions": {
"width": 5,
"height": 10
},
"id": 1,
"name": "A green door",
"price": 12.5,
"tags": [
"home",
"green"
]
},
"jsonSchema":{
"$schema": "http://json-schema.org/draft-07/schema",
"$id": "http://example.com/root.json",
"type": "object",
"title": "The Root Schema",
"description": "The root schema is the schema that comprises the entire JSON document.",
"default": {
},
"required": [
"checked",
"dimensions",
"id",
"name",
"price",
"tags"
],
"properties": {
"checked": {
"$id": "#/properties/checked",
"type": "boolean",
"title": "The Checked Schema",
"description": "An explanation about the purpose of this instance.",
"default": false,
"examples": [
false
]
},
"dimensions": {
"$id": "#/properties/dimensions",
"type": "object",
"title": "The Dimensions Schema",
"description": "An explanation about the purpose of this instance.",
"default": {
},
"examples": [
{
"height": 10.0,
"width": 5.0
}
],
"required": [
"width",
"height"
],
"properties": {
"width": {
"$id": "#/properties/dimensions/properties/width",
"type": "integer",
"title": "The Width Schema",
"description": "An explanation about the purpose of this instance.",
"default": 0,
"examples": [
5
]
},
"height": {
"$id": "#/properties/dimensions/properties/height",
"type": "integer",
"title": "The Height Schema",
"description": "An explanation about the purpose of this instance.",
"default": 0,
"examples": [
10
]
}
}
},
"id": {
"$id": "#/properties/id",
"type": "integer",
"title": "The Id Schema",
"description": "An explanation about the purpose of this instance.",
"default": 0,
"examples": [
1
]
},
"name": {
"$id": "#/properties/name",
"type": "string",
"title": "The Name Schema",
"description": "An explanation about the purpose of this instance.",
"default": "",
"examples": [
"A green door"
]
},
"price": {
"$id": "#/properties/price",
"type": "number",
"title": "The Price Schema",
"description": "An explanation about the purpose of this instance.",
"default": 0,
"examples": [
12.5
]
},
"tags": {
"$id": "#/properties/tags",
"type": "array",
"title": "The Tags Schema",
"description": "An explanation about the purpose of this instance.",
"default": [
],
"examples": [
[
"home",
"green"
]
],
"items": {
"$id": "#/properties/tags/items",
"type": "string",
"title": "The Items Schema",
"description": "An explanation about the purpose of this instance.",
"default": "",
"examples": [
"home",
"green"
]
}
}
}
}
}