Like XML, JSON also provides schema and the code has to validate the json instance with a schema. In this post, let us see how we can validate the given instance with its JSON schema.
The validator I would recommend is 'json-schema-validator'. The version I have used is 2.0.1, which supports both v3 and v4 Json schemas. You can take a look at the latest versions of the validator also.
Add the following in your pom.xml:
<dependency>
1) If the schema or the instance are strings, transform them to JsonNode objects:
And...that's all folks.
The validator I would recommend is 'json-schema-validator'. The version I have used is 2.0.1, which supports both v3 and v4 Json schemas. You can take a look at the latest versions of the validator also.
Add the following in your pom.xml:
<dependency>
<groupId>com.github.fge</groupId>
<artifactId>json-schema-validator</artifactId>
<version>2.0.1</version>
</dependency>
Then follow these steps:1) If the schema or the instance are strings, transform them to JsonNode objects:
ObjectMapper mapper = new ObjectMapper();
//json instance object
JsonNode instanceJsonObject = mapper.readTree(jsonInstance);
//json schema string to json object.
JsonNode schemaJsonObject = mapper.readTree(jsonSchema);
2) Next step is to get the json schema object:
//The schema factory supports both Json's v3 and v4 schemas. Most of the times, the default
//factory is enough.
JsonSchemaFactory schemaFactory = JsonSchemaFactory.byDefault();
JsonSchema schema = schemaFactory.getJsonSchema(schemaJsonObject );
3) Now the instance can be validated with the validate() of JsonSchema:
ListProcessingReport report = (ListProcessingReport)schema.validate(instanceNode);
The ListProcessing contains the valiation messages, the missing required field(s) details. To obtain those details, follow these steps:
if(!report.isSuccess()){
JsonNode reportRootNode = report.asJson();
if(rootNode.size() > 0){
JsonNode errorNode = rootNode.get(0);
JsonNode messageNode = errorNode.get("message");
if(messageNode != null){
logger.error(messageNode.asText());
}
JsonNode requiredNode = errorNode.get("required");
if(requiredNode != null) {
logger.error(requiredNode.toString());
}
JsonNode missingNode = errorNode.get("missing");
if(missingNode != null){
logger.error((missingNode.toString());
}
}
}
And...that's all folks.