Given the following class hierarchy, I would like Foo to be serialized differently depending on the context it is used in my class hierarchy.
public class Foo {
public String bar;
public String biz;
}
public class FooContainer {
public Foo fooA;
public Foo fooB;
}
I would like for the biz attribute to not show up in fooB when I serialize FooContainer. So the output would look something like the following.
{
"fooA": {"bar": "asdf", "biz": "fdsa"},
"fooB": {"bar": "qwer"}
}
I was going to use something JsonView, but that has to be applied at the mapper layer for all instances of a class, and this is context dependent.
On the Jackson user mailing list, Tatu gave the simplest solution (works in 2.0), which I will probably end up using for now. Awarding the bounty to jlabedo because the answer is an awesome example of how to extend Jackson using custom annotations.
public class FooContainer {
public Foo fooA;
@JsonIgnoreProperties({ "biz" })
public Foo fooB;
}
You could use a combination of a custom serializer with a custom property filter using JsonViews. Here is some code working with Jackson 2.0
Define a custom annotation:
Define some Views:
Then you can write your entities like this. Note that you may define your own annotation instead of using
@JsonView:Then, here is where the code begins 🙂
First your custom filter:
Then a custom
AnnotationIntrospectorthat will do two things:@FilterUsingViewannotation.Here is the code
Here is your custom serializer. The only thing it does is passing your annotation’s value to your custom filter, then it let the default serializer do the job.
Finally ! Let’s put this all together :