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

余生长醉 提交于 2019-12-20 05:03:04

问题


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"]
}

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

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?

Thanks.


回答1:


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.

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

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

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


来源:https://stackoverflow.com/questions/36075449/how-to-validate-a-json-schema-against-the-version-spec-it-specifies-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!