Monday, 25 May 2015

JSONPath and JSON Schema

JSONPath provides a JSON analogue to XPath.  JSONPaths come in one of several forms, including a JQuery-like pattern:

JSONPaths can be "definite" (i.e. single-valued):
$.id
or "indefinite" (i.e. multivalued):
$..id

They're cross-platform, but I've been using a Jayway library:
<dependency>
  <groupId>com.jayway.jsonpath</groupId>
  <artifactId>json-path</artifactId>
  <version>2.0.0</version>
</dependency>

This is based around a class JsonPath with straightforward static methods.  This adds a compilation overhead, so if you're using the same expression repeatedly you should look into the "compile" method, which gives a nonstatic version.

JSON schema is much less intuitive, and seems to have surprisingly little support in Java: http://json-schema.org/implementations.html
There's a useful online tool to generate a schema for a given JSON example:
http://jsonschema.net/#/

This seems to be the best publicized JSON schema library:
https://github.com/fge/json-schema-validator/

To build a schema object, you first need to convert it into Jackson's JSON types:
// Marshall schema
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree(config.getJsonSchema());

// Build schema object
final JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
jsonSchema = factory.getJsonSchema(actualObj);

Once the schema object is built, validating documents against it requires a similar set of steps:

ObjectMapper mapper = new ObjectMapper();
JsonNode jn = mapper.readTree(entity.toString());
ProcessingReport report = jsonSchema.validate(jn);
if (!report.isSuccess()) {
  throw new IllegalArgumentException(
  "Entity did not conform to configured schema.");
}

Helpfully, json-schema-validator comes with a set of example classes, which show it in action.

No comments:

Post a Comment