I have a pojo class where one of the flag isControl
which is of type Boolean.
When this property gets a non boolean value other than true or false
fasterxml jackson automatically converts the input value to true
. After debugging for few hours I find out that this is happening in the setter method setIsControl
.
I want to pass a custom message if input value for this property is non-boolean. I have written my own annotation to validate the input value for this property and return custom message if its not a boolean value but jackson binds the value before checking my custom validator.
Using jackson version >>> 2.6.3
. Any help will be appreciated.
Control.java
@JsonProperty(required = true)
@NotNull(message = "isControl cannot be null")
private Boolean isControl;
public Boolean getIsControl() {
return isControl;
}
@CheckBoolean(fieldName = "isControl")
public void setIsControl(Boolean isControl) {
this.isControl = isControl;
}
public class BooleanValidator implements ConstraintValidator<CheckBoolean, Boolean> {
private String fieldName;
@Override
public void initialize(CheckBoolean constraintAnnotation) {
this.fieldName = constraintAnnotation.fieldName();
}
@Override
public boolean isValid(Boolean value, ConstraintValidatorContext context) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(
String.format("The control flag %s should be either true or false", fieldName))
.addConstraintViolation();
if (value != null) {
boolean isBoolean;
if (value instanceof Boolean) {
isBoolean = ((Boolean)value).booleanValue();
System.out.println("var isBoolean: " +isBoolean);
return true;
} else if (value instanceof Boolean && Boolean.FALSE.equals(value)) {
isBoolean = ((Boolean)value).booleanValue();
return true;
} else {
return false;
}
}
return false;
}
}
Exception: