I am developing a Spring Boot web application that exposes REST APIs and I have trouble with JSON Serialization.
Let's say I have two classes A and B, that are in a one-to-many bidirectional relationship.
This means that I have something like this:
public class A {
private List<B> bList;
...
}
and
public class B {
private A owner;
...
}
When it comes to JSON serialize this, of course there is a loop.
And this is my problem:
- In API methods that focus on
A
(e.g. "give me the list of all As in the DB"), I would like a JSON serialization in which:A
objects do contain the list ofB
sB
objects do not contain their A owner
- In API methods that focus on
B
(e.g. "give me the list of allB
s in the DB"), I would like a JSON serialization in which:A
objects do not contain the list of theirB
sB
objects do contain theirA
owner
I believe I could get it to work with @JsonView
annotations, but I do not think it is an elegant solution. In my application (which has more than two classes) I'd need to create and manage at least 4 or 5 JsonViews: so in my model classes, for each attribute I'd have to manage a messy bunch of @JsonView
annotations. On the contrary, I believe that model classes should not be aware of the fact that they have different JSON representations depending on the API method.
I searched how to use custom JSON serializers, and found that Jackson allows to do that with its SimpleModule. However it seems that the SimpleModule does not allow to choose which serializer to use on a case-by-case basis (it just always uses the last added Serializer).
So I am a bit clueless now. Does anybody know a clean way to allow the Controllers choose how to serialize a Class?