Say I have a simple POJO like below annotated with Jackson 2.1 and Hibernate Validator 4.3.1 annotations:
final public class Person {
@JsonProperty("nm")
@NotNull
final public String name;
public Person(String name) {
this.name = name;
}
}
And I send JSON like such to a web service:
{"name": null}
Hibernate when it reports the ConstraintViolation uses the class member identifier "name" instead of the JsonProperty annotation value. Does anyone know if it is possible to make the Hibernate Validator look at the annotation of the class and use that value instead?
Unfortunately there is no easy way to do it. But here are some insights that can help you:
Parsing constraint violations
From the
ConstraintViolationException
, you can get a set ofConstraintViolation
, that exposes the constraint violation context:ConstraintViolation#getLeafBean()
: If it is a bean constraint, this method returns the bean instance in which the constraint is applied to.ConstraintViolation#getPropertyPath()
: Returns the path to the invalid property.From the property path, you can get the leaf node:
Then check if the type of the node is
PROPERTY
and get its name:Introspecting a class with Jackson
To get the available JSON properties from the leaf bean class, you can introspect it with Jackson (see this answer and this answer for further details):
Then filter the properties by comparing the leaf node name with the
Field
name from theBeanPropertyDefinition
:Using JAX-RS?
With JAX-RS (if you are using it), you can define an
ExceptionMapper
to handleConstraintViolationException
s:To use the
ObjectMapper
in yourExceptionMapper
, you could provide aContextResolver<T>
for it:Inject the
Providers
interface in yourExceptionMapper
:Lookup for your
ContextResolver<T>
and then get theObjectMapper
instance:If you are interested in getting
@XxxParam
names, refer to this answer.No, that's not possible. Hibernate Validator 5 (Bean Validation 1.1) has the notion of
ParameterNameProvider
s which return the names to reported in case method parameter constraints are violated but there is nothing comparable for property constraints.