Search code examples
javajsonjacksonhibernate-validator

Jackson and Hibernate Validator


Are there any online tutorial available to use Hibernate validator with Jackson for validating JSON? I am using Spring and Jackson now for JSON parsing. With Spring, I use MappingJacksonHttpMessageConverter to automatically translate the incoming JSON payload to Java object.

I would like to add validator annotations to the Java class. For example, if I have the Person class with "name" as one of the fields, I like to validate the JSON payload if the "name" element appears 1 time. If it appears more than 1 time in the payload, then I like the validator to kick in to reject the request.

Right now what I observed is that if there are multiple names in the payload, Jackson simply ignores and picks up the last one.

The Java object is not bound to any XML schema and the like.

What is the best practice for validating JSON?


Solution

  • Spring has JSR-303 support built in, see this chapter in the reference manual.

    If you are using Spring MVC, see here, you should just be able to annotate parameters to @RequestMapping methods with @Valid.