zeus1208
zeus1208

Reputation: 78

Using @JsonIgnore selectively on parent class fields

I have a Class A which is extended by multiple classes, say Class B, Class C and Class D. However I want only Class D to ignore super class fields during serialization. How do I implement this? If I use @JsonIgnore annotation on parent Class A, all child classes get impacted.

Upvotes: 0

Views: 5004

Answers (1)

Bentaye
Bentaye

Reputation: 9756

I can see 2 ways:

1 - You can use a JacksonAnnotationIntrospector to dynamically ignore fields, here we test if the field is from class A (see example below when serialising class C)

class CustomIntrospector extends JacksonAnnotationIntrospector {
    @Override
    public boolean hasIgnoreMarker(final AnnotatedMember m) {
        return m.getDeclaringClass() == A.class;
    }  
}

2 - You can use the @JsonIgnoreProperties annotation to ignore the fields you don't want (see example below on the definition of class D)

Then with the following class

class A {
    public String fieldA = "a";
}
class B extends A {
    public String fieldB = "b";
}
class C extends A {
    public String fieldC = "c";
}

@JsonIgnoreProperties(value = { "fieldA" })
class D extends A {
    public String fieldD = "d";
}

Then use the ObjectMapper

public static void main(String[] args) throws Exception {
    A a = new A();
    String jsonA = new ObjectMapper().writeValueAsString(a);
    System.out.println(jsonA);

    // No filtering, will output all fields
    B b = new B();
    String jsonB = new ObjectMapper().writeValueAsString(b);
    System.out.println(jsonB);

    // Using the CustomIntrospector to filter out fields from class A
    C c = new C();
    ObjectMapper mapper = new ObjectMapper().setAnnotationIntrospector(new CustomIntrospector());
    String jsonC = mapper.writeValueAsString(c);
    System.out.println(jsonC);

    // Using @JsonIgnoreProperties to filter out fields from class A
    D d = new D();
    String jsonD = new ObjectMapper().writeValueAsString(d);
    System.out.println(jsonD);
}

outputs

{"fieldA":"a"}
{"fieldA":"a","fieldB":"b"}
{"fieldC":"c"}
{"fieldD":"d"}

Upvotes: 3

Related Questions