JSON has became a de-facto standard for webservices, replacing XML web services. It has native support in web browser clients.
That makes JSON is the standard of choice for UI-oriented services. It has a good support on mobile devices. Also, it provides smaller data payload size compared to XML and it’s very sufficient for high-load systems as it saves a traffic. But what is for data validation? For XML web services there is a XML Schema. It comes ti mind, that similar standard for JSON should be called “JSON Schema”. And it really exists!
There are a number of libraries for working with JSON Schema, including validators, documentation generators and data processing.
For java, there is a library which implements JSON message validation: json-schema-validator. It uses jackson library as its’ core and can be used in any java environment.
Here is demo application project: json-schema-validator-demo
Code sample:
1import com.fasterxml.jackson.databind.JsonNode;
2import com.github.fge.jsonschema.main.JsonValidator;
3import com.github.fge.jsonschema.main.JsonSchemaFactory;
4import com.github.fge.jsonschema.core.report.ProcessingReport;
5import com.github.fge.jsonschema.core.util.AsJson;
6...
7
8JsonValidator VALIDATOR = JsonSchemaFactory.byDefault().getValidator();
9
10JsonNode schemaNode = ...
11JsonNode data = ...
12
13ProcessingReport report = VALIDATOR.validateUnchecked(schemaNode, data);
14
15final boolean success = report.isSuccess();
16
17final JsonNode reportAsJson = ((AsJson) report).asJson();Demo applicaiton: https://json-schema-validator.herokuapp.com/