如何根据它在Java中指定的版本规范验证json模式 [英] How to validate a json schema against the version spec it specifies in Java

查看:203
本文介绍了如何根据它在Java中指定的版本规范验证json模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出像这样的json模式..

Given a json schema like this..



    {
   "$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,在本例中为draft-04 ..

How to validate that this json schema conforms to the $schema it specifies, in this case the draft-04..

java中是否有可以执行此操作的软件包?
我可以使用 https://github.com/everit-org/json-架构或只是针对其架构验证json文档?

Are there any packages in java that can do this? Can I use something like https://github.com/everit-org/json-schema or is that only validating a json document against its schema?

谢谢。

推荐答案

从每个JSON模式链接的模式实际上是JSON模式的一种元模式,因此您实际上可以使用它来按照您的建议验证模式。

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.

假设我们已将元架构保存为名为 meta-schema.json 的文件,并将我们的潜在架构保存为 schema.json 。首先,我们需要一种方法来加载这些文件为 JSONObjects

Suppose we have saved the meta-schema as a file called meta-schema.json, and our potential schema as schema.json. First we need a way to load these files as JSONObjects:

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

我们可以加载元模式,并将其加载到json模式中你链接的库:

We can load the meta-schema, and load it into the json-schema library you linked:

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

根据您发布的示例,打印出架构有效!。但是如果我们要引入错误,例如通过将name字段的type更改为foo而不是string,我们会收到以下错误:

Given the example you posted, this prints "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:

Schema is invalid! #/properties/name/type: #: no subschema matched out of the total 2 subschemas

这篇关于如何根据它在Java中指定的版本规范验证json模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆