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";
}
else {
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 it's part of aHelper
class, I think it's okay to put some business logic (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 are optional. In case ifjson
doesn't exist, there is no point of getting into validation.