如果我有一个类层次结构,如A - > B,其中A是基类,如何在Jackson序列化期间指定仅包含基类中的字段并从子类中排除所有内容?我序列化的是B(子类)。
感谢帮助!!
答案 0 :(得分:1)
您可以使用Jackson JSON views中提及的this similar question。
此外,您可以编写an annotation introspector或Jackson JSON filter来排除子类中的所有内容。
我编写了一个示例,演示如何从具有特殊注释的层次结构中的类型中排除所有属性。
public class JacksonExcludeFromSubclass {
@Retention(RetentionPolicy.RUNTIME)
public static @interface IgnoreTypeProperties {};
public static class SuperThing {
public final String superField;
public SuperThing(String superField) {
this.superField = superField;
}
}
@JsonFilter("filter")
@IgnoreTypeProperties
public static class Thing extends SuperThing {
public final String thingField;
public Thing(String superField, String thingField) {
super(superField);
this.thingField = thingField;
}
}
public static class ExcludeFromSuperClass extends SimpleBeanPropertyFilter {
@Override
protected boolean include(BeanPropertyWriter writer) {
return true;
}
@Override
protected boolean include(PropertyWriter writer) {
if (writer instanceof BeanPropertyWriter) {
AnnotatedMember member = ((BeanPropertyWriter) writer).getMember();
return member.getDeclaringClass().getAnnotation(IgnoreTypeProperties.class) == null;
}
return true;
}
}
public static void main(String[] args) throws JsonProcessingException {
Thing t = new Thing("super", "thing");
ObjectMapper mapper = new ObjectMapper();
mapper.setFilters(new SimpleFilterProvider().addFilter("filter", new ExcludeFromSuperClass()));
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(t));
}
输出:
{
"superField" : "super"
}