【发布时间】:2017-03-07 18:52:15
【问题描述】:
我有一个 pojo 类,其中一个标志 isControl 是布尔类型。
当此属性获得除true or false 以外的非布尔值时,fastxml jackson 会自动将输入值转换为true。经过几个小时的调试,我发现这是在setter方法setIsControl中发生的。
如果此属性的输入值为非布尔值,我想传递自定义消息。我已经编写了自己的注释来验证此属性的输入值,如果它不是布尔值但杰克逊在检查我的自定义验证器之前绑定了该值,则返回自定义消息。
使用杰克逊版本>>> 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;
}
}
例外:
【问题讨论】:
标签: java json serialization jackson fasterxml