Reputation:
I am writing a REST API with a Java/Jersey/Jackson stack. All JSON parsing and generating is done with Jackson. The REST layer is handled by Jersey. It will be embedded in a Grizzly container.
In my API, I accept JSON in my endpoints. For example:
@POST
public Response post(final SomeObject input) {
return ...;
}
What is the best way to validate the input
? There are certain things I would like to validate:
input
must be not nullinput
must be not nullinput
must follow a regular expression (text fields)input
must be in a range (numeric fields)If possible, I would like to change my code as less as possible. That is, I prefer to annotate my classes, methods and parameters to integrate the validation.
Upvotes: 4
Views: 10473
Reputation: 15698
You can also BeanValidationApi (javax.validation.constraints) and then annotate your fields with @NotNull,@Pattern
, etc. Jersey also provides Bean Validation Support
Upvotes: 2
Reputation: 121692
You can use a JSON Schema.
And since you use Jackson, you can use my library which does exactly that.
However this means you'd need to change your logic so that you receive the JSON (as a JsonNode
) instead of the serialized POJO, and only then serialize to your POJO.
Upvotes: 4