1
votes

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

1 Answers

2
votes

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