3
我有一個對象圖,其中包含(對於本示例而言)Foo類型的子類的對象。 Foo類有一個名爲bar的屬性,我不想用我的對象圖序列化它。所以基本上我想要一種方式來說,只要你序列化一個Foo類型的對象,就輸出一切,但是不能輸出。如何從Jackson JSON序列化中全局刪除屬性?
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建議,包括代碼,我會最終使用(和制杆例如起見吸氣)從@JsonIgnore
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!
}
}
這可能是我的無知,但標記欄爲瞬態? – DwB 2012-02-09 19:00:55