Java使用JsonSchema实例,基于Springboot

先自定义一个json数据格式标准,放在一个json文件中,json文件放在resources下面

{
  "title" : "标题",
  "description" : "描述",
  "type" : "object",
  "properties" : {
    "name" : {
      "type" : "string"
    },
    "age" : {
      "type" : "number",
      "enum" : [10, 11]
    },
    "sex": {
      "type" : "boolean"
    }
  },
  "required": ["name", "age"]
}

再定义一个json数据,用于传入校验,同样放在resources下面

{
  "name": "a",
  "age": 10
}

加载出两个json文件,进行校验


import org.everit.json.schema.Schema;
import org.everit.json.schema.loader.SchemaLoader;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.junit.Test;

import java.io.InputStream;


public class TestJson {

    @Test
    public void TestJson() {

//        得到待校验的json数据
        InputStream inputStreamjson = getClass().getResourceAsStream("/getjson.json");
        JSONObject jsonObjectjson = new JSONObject(new JSONTokener(inputStreamjson));
        System.out.println("待校验的json数据:" + jsonObjectjson);


//        得到设定的标准json
        InputStream inputStreamjsonSchema = getClass().getResourceAsStream("/one.json");
        JSONObject jsonObjectSchema = new JSONObject(new JSONTokener(inputStreamjsonSchema));
        System.out.println("标准格式:"+jsonObjectSchema);

//        Schema对象加载设定的标准json
        Schema schema = SchemaLoader.load(jsonObjectSchema);
//        对得到的json数据进行校验
        schema.validate(jsonObjectjson);


    }


}

测试

当age为8时,测试不通过

当age为10时,测试通过

原文地址:https://www.cnblogs.com/lyd447113735/p/14836649.html