简体   繁体   English

如何根据Java中指定的版本规范验证JSON模式

[英]How to validate a json schema against the version spec it specifies in Java

Given a json schema like this.. 给定这样的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"]
}

How to validate that this json schema conforms to the $schema it specifies, in this case the draft-04.. 如何验证此json模式是否符合其指定的$ schema,在本例中为草案04。

Are there any packages in java that can do this? Java中是否有任何软件包可以做到这一点? Can I use something like https://github.com/everit-org/json-schema or is that only validating a json document against its schema? 我可以使用https://github.com/everit-org/json-schema之类的东西,还是仅根据其架构验证json文档?

Thanks. 谢谢。

The schema linked from every JSON schema is in fact a sort of "meta-schema" for JSON schemas, so you can in fact use it to validate a schema as you suggest. 实际上,从每个JSON模式链接的模式都是JSON模式的一种“元模式”,因此您实际上可以按照您的建议使用它来验证模式。

Suppose we have saved the meta-schema as a file called meta-schema.json , and our potential schema as schema.json . 假设我们已经将meta-schema保存为一个名为meta-schema.json的文件,并将潜在的模式保存为schema.json First we need a way to load these files as JSONObjects : 首先,我们需要一种将这些文件加载​​为JSONObjects

public static JSONObject loadJsonFromFile(String fileName) throws FileNotFoundException {
    Reader reader = new FileReader(fileName);
    return new JSONObject(new JSONTokener(reader));
}

We can load the meta-schema, and load it into the json-schema library you linked: 我们可以加载元模式,并将其加载到您链接的json模式库中:

JSONObject metaSchemaJson = loadJsonFromFile("meta-schema.json");
Schema metaSchema = SchemaLoader.load(metaSchemaJson);

Finally, we load the potential schema and validate it using the meta-schema: 最后,我们加载潜在的模式并使用元模式对其进行验证:

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());
}

Given the example you posted, this prints "Schema is valid!". 给定您发布的示例,它会显示“ Schema is valid!”。 But if we were to introduce an error, for example by changing the "type" of the "name" field to "foo" instead of "string" , we would get the following error: 但是,如果要引入错误,例如通过将"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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM