Match.json
{
"type": "object",
"properties": {
"number": { "type": "number" },
"street_name": { "type": "string" },
"street_type": { "enum": ["Street", "Avenue", "Boulevard"] }
}
}
test.json
{
"number": 1600,
"street_name": "Pennsylvania",
"street_type": "Avenue"
}
Json文件的位置放在resources目录下即可
校验代码
package com.learning.jonchema;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.everit.json.schema.Schema;
import org.everit.json.schema.ValidationException;
import org.everit.json.schema.loader.SchemaLoader;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.junit.Test;
import java.io.InputStream;
/**
* @author dell
*/
public class TestJson {
@Test
public void TestJson() {
//这个就是你设定的标准JSON
InputStream standard = getClass().getResourceAsStream("/Match.json");
//这个是你打算验证的JSON,这里我也用一份文件来存放,你也可以使用string或者jsonObject
InputStream verification = getClass().getResourceAsStream("/test.json");
JSONObject standardJSON = new JSONObject(new JSONTokener(standard));
JSONObject verificationJSON = new JSONObject(new JSONTokener(verification));
Schema schema = SchemaLoader.load(standardJSON);
try {
schema.validate(verificationJSON);
System.out.println("校验成功!");
} catch (ValidationException e) {
System.out.println("校验失败!");
System.out.println(e.getErrorMessage());
}
}
}
运行结果是 校验成功!
当把test.json文件的内容换成
{
"number": "1600",
"street_name": "Pennsylvania",
"street_type": "Avenue"
}
运行结果是
校验失败!
expected type: Number, found: String, 因为提供的号码类型错误,则无效
更多的校验规则可以看JSONSchema规范(中文版)