[英]How to validate a json schema against the version spec it specifies in Java
給定這樣的json模式。
{ "$schema": "http://json-schema.org/draft-04/schema#", "title": "Product", "description": "A product from Acme's catalog", "type": "object", "properties": { "id": { "description": "The unique identifier for a product", "type": "integer" }, "name": { "description": "Name of the product", "type": "string" }, "price": { "type": "number", "minimum": 0, "exclusiveMinimum": true } }, "required": ["id", "name", "price"] }
如何驗證此json模式是否符合其指定的$ schema,在本例中為草案04。
Java中是否有任何軟件包可以做到這一點? 我可以使用https://github.com/everit-org/json-schema之類的東西,還是僅根據其架構驗證json文檔?
謝謝。
實際上,從每個JSON模式鏈接的模式都是JSON模式的一種“元模式”,因此您實際上可以按照您的建議使用它來驗證模式。
假設我們已經將meta-schema保存為一個名為meta-schema.json
的文件,並將潛在的模式保存為schema.json
。 首先,我們需要一種將這些文件加載為JSONObjects
:
public static JSONObject loadJsonFromFile(String fileName) throws FileNotFoundException {
Reader reader = new FileReader(fileName);
return new JSONObject(new JSONTokener(reader));
}
我們可以加載元模式,並將其加載到您鏈接的json模式庫中:
JSONObject metaSchemaJson = loadJsonFromFile("meta-schema.json");
Schema metaSchema = SchemaLoader.load(metaSchemaJson);
最后,我們加載潛在的模式並使用元模式對其進行驗證:
JSONObject schemaJson = loadJsonFromFile("schema.json");
try {
metaSchema.validate(schemaJson);
System.out.println("Schema is valid!");
} catch (ValidationException e) {
System.out.println("Schema is invalid! " + e.getMessage());
}
給定您發布的示例,它會顯示“ Schema is valid!”。 但是,如果要引入錯誤,例如通過將"name"
字段的"type"
更改為"foo"
而不是"string"
,則會出現以下錯誤:
Schema is invalid! #/properties/name/type: #: no subschema matched out of the total 2 subschemas
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.