【发布时间】:2012-02-09 18:01:38
【问题描述】:
我有一个对象图,其中包含(就本示例而言)类型为 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 成为吸气剂)
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!
}
}
【问题讨论】:
-
这可能是我的无知表现,但是将 bar 标记为瞬态呢?