Validate JSON in Java with JSON Schema

Describe and validate your JSON documents

I programmed a lot with XML and XML Schema helped me to define which elements and attributes can appear in a document. So I always wanted a grammar for JSON too.

JSON Schema is exactly what I wanted. It has the following advantages:
* describes existing data formats
* provides human- and machine-readable documentation
* validates data

I tried two json-schema validator implementations for java: Everit and Networknt. I like the validator schema from Everit because of the similarity to the Bean Validation API. But if you use Jackson than Networknt is a good choice. Now I show an example with Networknt.

This is simple product schema product.schema.json .

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Product",
  "description": "A product from the 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
    }
  },
  "required": ["id", "name", "price"]
}

And if you want to validate a JSON document called product.json than do the following:

JsonSchemaFactory factory =
  JsonSchemaFactory.getInstance(VersionFlag.V7);
InputStream is =  
  getClass()
  .getResourceAsStream("/product.schema.json");
schema = factory.getSchema(is);

JsonNode node =
  mapper.readTree(
    getClass()
    .getResourceAsStream("/product.json"));

Set<ValidationMessage errors = schema.validate(node);

Just read in the JSON Schema. Then map the JSON document to a JsonNode and call schema.validate(). That’s it.

I have shown you how to validate a JSON document which is very useful for automated testing and validating client submitted data. The whole implementation of this example and more can be found on Github.

Links
JSON-Schema
Everit-org json-schema-validator
Networknt json-schema-validator