我有一个 pojo 类,其中标志之一isControl
这是布尔类型。
当此属性获得除以下以外的非布尔值时true or false
fastxml jackson 自动将输入值转换为true
。经过几个小时的调试后我发现这是在setter方法中发生的setIsControl
.
如果此属性的输入值是非布尔值,我想传递自定义消息。我编写了自己的注释来验证此属性的输入值,如果它不是布尔值,则返回自定义消息,但 Jackson 在检查我的自定义验证器之前绑定了该值。
使用杰克逊版本>>>2.6.3
。任何帮助将不胜感激。
控制.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;
}
}
例外:
有两种方法可以做到这一点,假设您将布尔字段映射为哈迪回答的对象类型 -
1.自定义setter方法 -
public class DTO {
String key1;
Object booleanKey;
public Object getBooleanKey() {
return booleanKey;
}
public void setBooleanKey(Object booleanKey) {
if (booleanKey instanceof Boolean) {
this.booleanKey = booleanKey;
} else {
// custom code here
}
}
public String getKey1() {
return key1;
}
public void setKey1(String key1) {
this.key1 = key1;
}
}
2. 编写自定义解串器 -
class BooleanKeyDeserializer extends JsonDeserializer<Object> {
@Override
public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
Object object = p.readValueAs(Object.class);
if (!(object instanceof Boolean)) {
// custom code here
}
return object;
}
}
注释您要执行自定义反序列化的字段 -
class DTO {
String key1;
@JsonDeserialize(using = BooleanKeyDeserializer.class)
Object booleanKey;
//setters getters
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)