4

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 null
  • certain fields of input must be not null
  • certain fields of input must follow a regular expression (text fields)
  • certain fields of 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.

  • 1
    Have a look at this: https://jersey.java.net/documentation/latest/bean-validation.html – Baderous Jan 12 '15 at 09:20
  • Json validator may be helpful to you. See this http://stackoverflow.com/questions/2499126/json-schema-validation-using-java – Rahul Jan 12 '15 at 09:21

2 Answers2

4

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.

fge
  • 119,121
  • 33
  • 254
  • 329
2

You can also BeanValidationApi (javax.validation.constraints) and then annotate your fields with @NotNull,@Pattern, etc. Jersey also provides Bean Validation Support

sol4me
  • 15,233
  • 5
  • 34
  • 34