JSON Validator JavaIn 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:
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 Next TopicPseudocode Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India