我有一个POJO类,其中一个标志isControl
是布尔类型。
当该属性获得一个非布尔值而不是true或false
时,fasterxml jackson会自动将输入值转换为true
。经过几个小时的调试,我发现这是发生在setter方法setIsControl
中。
如果此属性的输入值不是布尔值,我想传递自定义消息。我编写了自己的注释来验证此属性的输入值,并在其不是布尔值时返回自定义消息,但jackson会在检查我的自定义验证器之前绑定该值。
使用的Jackson版本 >>> 2.6.3
。任何帮助将不胜感激。
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;
}
}
异常:
Jackson 2.9
已经实现了这个功能:ALLOW_COERCION_OF_SCALARS
。 - second