Validation and deserialization are separate concerns, so I would tie them together only if I really need to, e.g. if you really must use JSON Schemas. But if you are free to choose your own way to declare the constraints, I recommend bean validation, e.g. a JAX-RS resource like this (note the @Valid
annotation):
@Path("ping")
public class PingBoundary {
@POST
public String ping(@NotNull @Valid Person addressee) {
return "Hi " + addressee.getName() + "!";
}
}
And a payload class like this (using the lombok @Data annotation):
@Data
public class Person {
private String name;
@Min(0)
private short age;
}
Passing an invalid age
of -2 gives you a 400 Bad Request
with a helpful response body:
{
"classViolations": [],
"exception": null,
"fieldViolations": [],
"parameterViolations": [
{
"constraintType": "PARAMETER",
"message": "must be greater than or equal to 0",
"path": "ping.addressee.age",
"value": "-2"
}
],
"propertyViolations": [],
"returnValueViolations": []
}
Note that you should pass -parameters
to the compiler, or the path
would be ping.arg0.age
.