I'm currently using a JSON Schema Validator in conjunction with Gson to handle exceptions and validate json requests made to an API.
The validator can return multiple exceptions when comparing a request with a schema. The sample from the repository is:
try {
schema.validate(rectangleMultipleFailures);
}
catch (ValidationException e) {
System.out.println(e.getMessage());
e.getCausingExceptions().stream()
.map(ValidationException::getMessage)
.forEach(System.out::println);
}
And my implementation of the try catch (missing the catch obviously) is:
try (InputStream inputStream = this.getClass().getResourceAsStream("SupplierSchemaIncoming.json")) {
JSONObject rawSchema = new JSONObject(new JSONTokener(inputStream));
Schema schema = SchemaLoader.load(rawSchema);
// Throws a ValidationException if requestJson is invalid:
schema.validate(new JSONObject(requestJson));
}
catch (ValidationException ve) {
System.out.println(ve.toJSON().toString());
}
As you can see above, one option is to return all of the errors as a single JSON.
{
"pointerToViolation": "#",
"causingExceptions": [{
"pointerToViolation": "#/name",
"keyword": "type",
"message": "expected type: String, found: Integer"
}, {
"pointerToViolation": "#/type",
"keyword": "type",
"message": "expected type: String, found: Integer"
}],
"message": "2 schema violations found"
}
However, I'm stumped on how to get the exception to return an array of SchemaError objects (below) which I can parse however I want.
package domainObjects;
import com.google.gson.annotations.Expose;
public class SchemaError {
@Expose
String pointerToViolation;
@Expose
String keyword;
@Expose
String message;
public SchemaError() {}
public String getPointerToViolation() {
return pointerToViolation;
}
public void setPointerToViolation(String pointerToViolation) {
this.pointerToViolation = pointerToViolation;
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}