另一种方法是使用 BeanDeserializerModifier:
private static class BeanDeserializerModifierForIgnorables extends BeanDeserializerModifier {
private java.lang.Class<?> type;
private List<String> ignorables;
public BeanDeserializerModifierForIgnorables(java.lang.Class clazz, String... properties) {
ignorables = new ArrayList<>();
for(String property : properties) {
ignorables.add(property);
}
this.type = clazz;
}
@Override
public BeanDeserializerBuilder updateBuilder(
DeserializationConfig config, BeanDescription beanDesc,
BeanDeserializerBuilder builder) {
if(!type.equals(beanDesc.getBeanClass())) {
return builder;
}
for(String ignorable : ignorables) {
builder.addIgnorable(ignorable);
}
return builder;
}
@Override
public List<BeanPropertyDefinition> updateProperties(
DeserializationConfig config, BeanDescription beanDesc,
List<BeanPropertyDefinition> propDefs) {
if(!type.equals(beanDesc.getBeanClass())) {
return propDefs;
}
List<BeanPropertyDefinition> newPropDefs = new ArrayList<>();
for(BeanPropertyDefinition propDef : propDefs) {
if(!ignorables.contains(propDef.getName())) {
newPropDefs.add(propDef);
}
}
return newPropDefs;
}
}
您可以使用以下方法将修改器注册到 ObjectMapper:
BeanDeserializerModifier modifier = new BeanDeserializerModifierForIgnorables(YourType.class, "name");
DeserializerFactory dFactory = BeanDeserializerFactory.instance.withDeserializerModifier(modifier);
ObjectMapper mapper = new ObjectMapper(null, null, new DefaultDeserializationContext.Impl(dFactory));
然后忽略定义的属性。如果您使用 @JsonAnySetter 注解,则可以忽略 updateBuilder 方法。
问候,马丁