This is what i wrote to validate json to the given schema.
public void validateJsonSchema(ObjectNode jsonSchema, ObjectNode json) throws InvalidRequestException { String errorMessage = null; if (json != null) { if(jsonSchema == null) { errorMessage = "json exist in request but there is no schema to validate it against"; } try { JsonSchema jsonSchema = JsonSchemaFactory.byDefault().getJsonSchema(jsonSchema); ProcessingReport processingReport = jsonSchema.validate(json); if (!processingReport.isSuccess()) { StringBuilder sb = new StringBuilder(); processingReport.forEach(jsonError -> sb.append(String.format("[%s] ", jsonError))); errorMessage = String.format("json validation failed. Errors: %s", sb.toString()); } } catch (ProcessingException e) { errorMessage = String.format("json validation threw ProcessingException. Error Message: %s", e.getMessage()); } } if (errorMessage != null) { throw new InvalidRequestException(errorMessage); } }
Here are few things that i had in my mind while writing this code
-
I don’t want to return anything from the method. Schema is either
valid
orinvalid
. In case ofinvalid
, i just throw an exception. Since its part of aHelper
class, i think its okay to put some business logc (throwing exception) with in this code. -
I like 1 point of return or 1 point of exception throwing. Thats why i am using
errorMessage
to capture any error and if it exists, throw it at the end. By this approach, the code readability is much better. -
The
jsonSchema
andjson
both could are optional. In case ifjson
doesn’t exist, there is no point of getting into validation.