svguerin3 svguerin3 - 1 month ago 38
Android Question

Java/Android - Validate String JSON against String schema

I am having trouble finding the most simple way to validate a JSON String against a given JSON-schema String (for reference, this is in Java, running in an Android app).

Ideally, I'd like to just pass in a JSON String and a JSON-schema String, and it returns a boolean as to whether it passes the validation. Through searching, I have found the following 2 promising libraries for accomplishing this:

http://jsontools.berlios.de/

https://github.com/fge/json-schema-validator

However, the first one seems fairly outdated with poor support. I implemented the library into my project, and even with their JavaDocs, I was unable to tell how to properly build a "Validator" object for validation.

Similar story with the 2nd one, which seems to be up-to-date with good test code. However, for what I want to do, which is very simple, it seems to be a bit daunting and confusing as to how to specifically accomplish what I want (even after looking at the ValidateServlet.java file).

Curious if anyone has any other suggestions on a good way to accomplish this (from what it seems), simple task that need, or if I perhaps need to stick with the 2nd option from above? Thanks in advance!

Answer

This is essentially what the Servlet you linked to does, so it may not be a one-liner but it still is expressive.

useV4 and useId as specified on the servlet, are for specifying validations option for Default to draft v4 and Use id for addressing.

You can see it online: http://json-schema-validator.herokuapp.com/

public boolean validate(String jsonData, String jsonSchema, boolean useV4, boolean useId) throws Exception {
   // create the Json nodes for schema and data
   JsonNode schemaNode = JsonLoader.fromString(jsonSchema); // throws JsonProcessingException if error
   JsonNode data = JsonLoader.fromString(jsonData);         // same here

   JsonSchemaFactory factory = JsonSchemaFactories.withOptions(useV4, useId);
   // load the schema and validate
   JsonSchema schema = factory.fromSchema(schemaNode);
   ValidationReport report = schema.validate(data);

   return report.isSuccess();
}
Comments