1

If I have a class hierarchy like A -> B, where A is the base class, how can I specify during Jackson serialization to only include fields from base class and exclude everything from the subclass? What I am serializing is B (the subclass) though.

Appreciate the help!!

sobychacko
  • 5,099
  • 15
  • 26

1 Answers1

1

You can use the Jackson JSON views as it is mentioned in this similar question.

Also you can write an annotation introspector or a Jackson JSON filter which would exclude everything from the subclass.

I've written an example demonstrating how to exclude all the properties from a type in hierarchy that has a special annotation.

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));
    }

Output:

{
  "superField" : "super"
}
Community
  • 1
  • 1
Alexey Gavrilov
  • 10,593
  • 2
  • 38
  • 48