【发布时间】:2018-08-22 05:39:42
【问题描述】:
我有一个 A 类,它由多个类扩展,例如 B 类、C 类和 D 类。
但是,我只希望 Class D 在序列化期间忽略超类字段。
我该如何实施?如果我在父类A 上使用@JsonIgnore 注释,所有子类都会受到影响。
【问题讨论】:
标签: json serialization annotations jackson jersey
我有一个 A 类,它由多个类扩展,例如 B 类、C 类和 D 类。
但是,我只希望 Class D 在序列化期间忽略超类字段。
我该如何实施?如果我在父类A 上使用@JsonIgnore 注释,所有子类都会受到影响。
【问题讨论】:
标签: json serialization annotations jackson jersey
我可以看到两种方式:
1 - 您可以使用JacksonAnnotationIntrospector 来动态忽略字段,这里我们测试该字段是否来自类A(请参见下面的序列化类C 的示例)
class CustomIntrospector extends JacksonAnnotationIntrospector {
@Override
public boolean hasIgnoreMarker(final AnnotatedMember m) {
return m.getDeclaringClass() == A.class;
}
}
2 - 您可以使用@JsonIgnoreProperties 注释来忽略您不想要的字段(参见下面关于类D 的定义的示例)
然后用下面的类
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";
}
然后使用 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);
}
输出
{"fieldA":"a"}
{"fieldA":"a","fieldB":"b"}
{"fieldC":"c"}
{"fieldD":"d"}
【讨论】: