Skip to content

JSON Schema Support

bolerio edited this page Sep 5, 2014 · 6 revisions

JSON Schema is a standard for specifying how a JSON document should look like. Things like what properties of an object are required and what their types should be, how many elements an array should have and what their types should be etc. It is a very powerful and flexible, yet easy to use standard. XML has its XML Schema, so JSON has its JSON Schema.

When using JSON as the main data structure of your application, it is all the more important to validate the data you are working in since you don't have a compiler to do the job for you. So as of version 1.3, mJson supports the JSON schema standard (draf v4). The implementation has been fully test using the official JSON Schema test suite at https://github.com/json-schema/JSON-Schema-Test-Suite.

To use it, simply construct a Json.Schema object and call its validate method. If your schema uses absolute references, the implementation will try to load them using the standard java.net HTTP API. You can also provide the URI of the schema, and the implementation will load it. You can provide both the URI and the schema document in which case the implementation will simply assume the provided URI is the URI of the document for the purposes of resolving references. As a consequence, any reference with the same URI as the document URI will be interpreted as relative and no attempt at an HTTP connection will be made. Here are a few example of creating a schema instance:

// A simple schema that accepts only JSON objects with a mandatory property 'id'.
Json.Schema schema = Json.schema(Json.object("type", "object", "required", Json.array("id")));

// A schema from a remote URI
Json.Schema schema = Json.schema(new URI("http://mycompany.org/schemas/mydata.json"));

Here are some resources for learning about JSON Schema:

Clone this wiki locally