实际上,从每个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!”。但是,如果我们通过改变引入一个错误,例如
"type"在的
"name"领域
"foo",而不是
"string",我们会得到以下错误:
Schema is invalid! #/properties/name/type: #: no subschema matched out of the total 2 subschemas



