实际上,从每个JSON模式链接的模式都是JSON模式的一种“元模式”,因此您实际上可以按照您的建议使用它来验证模式.
假设我们已将元模式保存为名为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!”.但是,如果要引入错误,例如通过将“名称”字段的“类型”更改为“ foo”而不是“ string”,则会出现以下错误:
Schema is invalid! #/properties/name/type: #: no subschema matched out of the total 2 subschemas