Javatpoint Logo
Javatpoint Logo

JSON Validator Java

In Java, JSON, i.e., JavaScript Object Notation, plays a very important role in manipulating server-side response. In Java, we can validate JSON documents against a JSON schema. In order to perform the validation, we use the networknt JSON Schema validator library.

The reason for using this library is that it uses Jackson as a JSON library and supports the latest JSON Schema version. The networknt library is a Java implementation of the JSON Schema Core Draft v4, v6, v7, and v2019-09(Which we use in our example) specification for JSON schema validation. It has Jackson as a default JSON parser.

First, we take an example of JSON document and JSON schema, which we use in our program to perform validation.

JSON Document

JSON Schema

We add the following dependency in our pom.xml file.

We can also use the org.everit.json library for validating the JSON object. To use it, we need to add the following dependency in our pom.xml file:

In our case, we use the networknt library of Java.

We use the following steps to validate the JSON document:

  1. Create a new maven project.
  2. Add the JSON schema validator dependency in our pom.xml file.
  3. Read the data and the schema from the JSON document using ObjectMapper.
  4. Use validate() method of the JsonSchemaFactory to validate the JSON document.
  5. Store the returned result in the validation set print it on the screen.

Everything is set up now, so we can implement the actual code of validating the JSON document.

JsonValidatorExample.java

Description

In the above code, we use the VersionFlag. To obtain the JsonSchemaFactory, it is required to pass that version flag in the constructor. In our case, we use the 2019-09 version of JSON Schema.

We also use a custom helper method, i.e., inputStreamFromClasspath(), to load both the files from the classpath. We create an instance of the Jackson ObjectMapper class to read the JSON data from the InputStream. After that, we parse that InputStream data into a JsonNode object. Using the instance of the JsonSchemaFactory, we obtain the JsonSchema object to validate the JsonNode. We create a set of validation errors that contains one or more ValidationMessage objects. The validation set will be empty when there is no validation error.

Output

JSON Validator Java
Next TopicPseudocode Java





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA