JSON Validation with JSON Schema

May 10, 2014 1 minutes read

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:

import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jsonschema.main.JsonValidator;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.core.util.AsJson;

JsonValidator VALIDATOR  = JsonSchemaFactory.byDefault().getValidator();

JsonNode schemaNode = ...
JsonNode data = ...

ProcessingReport report = VALIDATOR.validateUnchecked(schemaNode, data);

final boolean success = report.isSuccess();

final JsonNode reportAsJson = ((AsJson) report).asJson();

Demo applicaiton: https://json-schema-validator.herokuapp.com/

See Also

Java-protobuf-format: Easy Protobuf-to-JSON Serialization in Java

If you need Google Protobuf-to-JSON serialization (and vice versa) there is quick solution. Protobuf-java-format library provides serialization of protobuf-generated java classes to number of formats: JSON, XML, HTML, Java property file format, Smile, CoachDB.

Here is a step-by-step instruction.

Webapp Inter-Communication in Tomcat

Sometimes you need to access services deployed in one web application from another web application within same application server. For Tomcat there is not so many options to do it. In this article we’ll discuss you how to use JMX for communication between web applications.

Getting More Entropy in Java on Linux

Setting entropy pool for Java server on linux is fair simple. Just add a system property to specify a device to read from.

logo   Never miss a story, subscribe to our newsletter