Enterprise Java

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:

1
2
3
4
5
<dependency>
    <groupId>com.networknt</groupId>
    <artifactId>json-schema-validator</artifactId>
    <version>1.0.42</version>
</dependency>

Now we can validate our JSON document in Java:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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:

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

You can find the example source code on GitHub.

Published on Java Code Geeks with permission by Michael Scharhag, partner at our JCG program. See the original article here: JSON Schema validation in Java

Opinions expressed by Java Code Geeks contributors are their own.

Michael Scharhag

Michael Scharhag is a Java Developer, Blogger and technology enthusiast. Particularly interested in Java related technologies including Java EE, Spring, Groovy and Grails.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Michael Reed
Michael Reed
3 years ago

Michael,

Good article, this has really helped me out. I do have a question for you though. How would I validate multiple schemas where schema A references schema B?

Edgar
Edgar
2 years ago

Hi, I want to customize validation errors, using my owns

Back to top button