Saturday, 6 August 2016

JSON Schema

It comes as a surprise that many people using json have never heard of json schema. JSON schema is similar to XSD's in the xml world.

Why use a schema?
Sometimes people argue for schemaless designs, however the argument is generally against not documenting schemas, as schema's are always present, they are just scattered in the code instead of in one defined place. For small simple json api's you can get away with not documenting your interfaces, however as api's grow in size and functionality it is useful to have a document that defines valid structures for messages going back and forth. Having this document defined in a standard notation means that it is parseable by a machine, which means the schema can be used to validate messages, manage api migrations and provide type information and documentation.

So how to use it?
The are many online resources to learn json-schema itself, such as the main site at
There are also some simple examples at

I have developed some example code which uses jsonschema2pojo to generate java objects from a jsonschema, then use the objects to marshall java objects from json, and validate the object and restrictions. The code can be found at:

1.  The schema's are defined under src/main/resources/schema.  There are 2 schema's they are independent and do not reference each other

2. Next we use org.jsonschema2pojo maven plugin to generate java object from the schema's. The jsonschema2pojo maven plugin can also generate JSR303 annotations which can be used for validation, using hibernate validator or any other jsr303 compliant validator.

3. There are tests under src/test/java which show usage examples such as marshalling an object from json, then validating the marshalled based on constraints defined in the schema. Below is a snippet from one of the tests

    //1. initialise object mapper
    ObjectMapper mapper = new ObjectMapper();

    //2. load json
    FileInputStream jsonInputStream = new FileInputStream("src/test/resources/ValidStudent.json");

    //3. map json to object
    Student student = mapper.readValue(jsonInputStream, Student.class);

    //4. create a validator
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    //5. validation errors if any
    Set<ConstraintViolation<Student>> validationResults = validator.validate(student);

No comments:

Post a Comment