我有一个对象图,其中包含对象,这些对象是(针对此示例)类型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}
}
谢谢, Ransom
编辑:使用了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!
}
}