JsonSchema的使用

在系统交互之间,采用Json的数据格式执行协议,来完成数据传输,算是前置校验吧

省去schema文件的编写,大致内容如下,网上copy的

{
... 
 "vegetables":  { 
   "type":  "array", 
   "items":  {  "$ref":  "#/definitions/veggie"  } 
 } 
   }, 
   "definitions":  { 
 "veggie":  { 
   "type":  "object", 
   "required":  [  "veggieName",  "veggieLike"  ], 
   "properties":  { 
     "veggieName":  { 
       "type":  "string", 
       "description":  "The name of the vegetable." 
     }, 
     "veggieLike":  { 
       "type":  "boolean", 
       "description":  "Do I like this vegetable?" 
     } 
...}

只使用代码描述,不在进行过多赘述,我不太喜欢说话

抽象出大致要使用的顶级接口Complier,好了我似乎特别喜欢Complier,好多都是它。

public interface Complier {

    void complie(byte[] bytes);
}

实现顶级接口Complier

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.main.JsonSchema;
import com.github.fge.jsonschema.main.JsonSchemaFactory;

/**
 * @Description //TODO
 * @Author taren.Tian
 * @Date 14:59 2019/8/16
 **/
public class MyDataComplier implements Complier {

private JsonSchema schema;

private final ObjectMapper objectMapper = new ObjectMapper();

public MyDataComplier() {
    try {
        //读入自定义的schemas文件
        JsonNode sh = objectMapper.readTree(this.getClass()
                .getClassLoader()
                .getResourceAsStream("schemas/yourJson.json"));
        final JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
        schema = factory.getJsonSchema(sh);
    } catch (Exception e) {

    }
}

@Override
public void complie(byte[] bytes) {
    try {
        JsonNode jsonNode = objectMapper.readTree(bytes);
        //先校验数据的格式 然后进行业务逻辑的处理
        ProcessingReport report = schema.validate(jsonNode);
        if (!report.isSuccess()) {
            throw new Exception(report.toString());
        }
        //doSomething()
    } catch (Exception e) {

    }
}
}

你可能感兴趣的:(JsonSchema的使用)