先自定義一個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時,測試通過