I have an object graph that contains objects that are (for purposes of this example) subclasses of type Foo. The Foo class has an attribute on it called bar that I do not want to be serialized with my object graph. So basically I want a way to say, whenever you serialize an object of type Foo, output everything but 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}
}
Thanks,
Ransom
Edit: Used StaxMan suggestion, including code that I would end up using (and made bar a getter for example’s sake)
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!
}
}
Aside from
@JsonIgnoreor@JsonIgnoreProperties(esp. via Mix-in Annotations), you can also define specific types to be globally ignored with ‘@JsonIgnoreType’. For third-party types, this too can be applied as a mix-in annotation.