我有一个对象图,它包含Foo类型的子类对象。Foo类上有一个名为bar的属性,我不想用我的对象图序列化它。所以基本上,我想用一种方法说,无论何时序列化Foo类型的对象,都要输出除bar之外的所有内容。
class Foo { // this is an external dependency
public long getBar() { return null; }
}
class Fuzz extends Foo {
public long getBiz() { return null; }
}
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
// I want to set a configuration on the mapper to
// exclude bar from all things that are type Foo
Fuzz fuzz = new Fuzz();
System.out.println(mapper.writeValueAsString(fuzz));
// writes {"bar": null, "biz": null} what I want is {"biz": null}
}
谢谢,赎金
编辑:使用了StaxMan的建议,包括我最终会使用的代码(并使bar成为一个getter)
interface Mixin {
@JsonIgnore long getBar();
}
class Example {
public static void main() {
ObjectMapper mapper = new ObjectMapper();
mapper.getSerializationConfig().addMixInAnnotations(Foo.class, Mixin.class);
Fuzz fuzz = new Fuzz();
System.out.println(mapper.writeValueAsString(fuzz));
// writes {"biz": null} whoo!
}
}
除了@JsonIgnore
或@JsonIgnoreProperties
(特别是通过注释中的混合),您还可以使用'@JsonIgnoreType'定义要全局忽略的特定类型。对于第三方类型,这也可以作为混合注释应用。