mscharhag, Programming and Stuff;

A blog about programming and software development topics, mostly focused on Java technologies including Java EE, Spring and Grails.

Thursday, 23 July, 2020

JSON Schema validation in Java

In this post we will see how to validate a JSON document against a JSON Schema in Java. We will use the same JSON document and Schema as in the previous post about JSON Schema.

You can find both as text files on GitHub: JSON document and JSON Schema.

We use the networknt JSON Schema validator library in this example. This library seems like a good fit because it supports the latest JSON Schema version (2019-09) and uses Jackson as JSON library. This makes it easy to integrate JSON Schema validation in Spring (hint: upcoming blog post).

We need to add the following dependency to our project:


Now we can validate our JSON document in Java:

private static InputStream inputStreamFromClasspath(String path) {
    return Thread.currentThread().getContextClassLoader().getResourceAsStream(path);

public static void main(String[] args) throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    JsonSchemaFactory schemaFactory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V201909);

    try (
            InputStream jsonStream = inputStreamFromClasspath("example.json");
            InputStream schemaStream = inputStreamFromClasspath("example-schema.json")
    ) {
        JsonNode json = objectMapper.readTree(jsonStream);
        JsonSchema schema = schemaFactory.getSchema(schemaStream);
        Set<ValidationMessage> validationResult = schema.validate(json);

        // print validation errors
        if (validationResult.isEmpty()) {
            System.out.println("no validation errors :-)");
        } else {
            validationResult.forEach(vm -> System.out.println(vm.getMessage()));

When obtaining a JsonSchemaFactory we need to pass a VersionFlag. This defines the JSON Schema version we want to use (here: 2019-09).

We then use a small helper method to load both files from the classpath. A Jackson ObjectMapper instance is used to read the JSON data from the InputStream and parse it into a JsonNode object. From the JsonSchemaFactory we can obtain a JsonSchema object which can then be used validate the JsonNode. In case of validation errors the returned Set will contain one or more ValidationMessage objects. If the returned Set is empty, no validation errors were found.

If we accidentally set the painting height to a negative number in our JSON document, we will get the following validation message:

$.dimension.height: must have a minimum value of 1

You can find the example source code on GitHub.

Leave a reply