I have a class with
(disclaimer, I am writing in Kotlin, but I translate it into Java so more people can read it)
@JsonIdentityInfo(
ObjectIdGenerators.PropertyGenerator.class,
"id"
)
public class Foo implements Serializable {
public int id;
public List<Foo> fooList;
}
I want to serialize another object which contains a list of Foo
s, but I want all entries in the serialized fooList
to be IDs, not objects. One solution that came to mind was to sort them topologically in reverse order before serialization, as they form a directed acyclic graph. But that's obviously not a perfect solution, so I'm wondering if there's an annotation or an otherwise clean Jackson way to do something like that.
EDIT:
The class that contains a list of Foo looks like this:
public class Bar implements Serializable {
public List<Foo> fooList;
}
And when I deserialize a Bar
instance from this JSON:
{
"fooList": [
{
"id": 0,
"fooList": [1]
},
{
"id": 1,
"fooList": []
}
]
}
And then I serialize it back, I want the output to be the same as the input, but instead it's this:
{
"fooList": [
{
"id": 0,
"fooList": [
{
"id": 1,
"fooList": []
}
]
},
1
]
}
You could create a class that extends from
Foo
class to offer an alternative serialization forfooList
using the annotation@JsonGetter
, like a wrapper.Foo
class:Bar
class:FooFooJsonSimplifiedSerializationWrapper
is theFoo
wrapper for serialization and it has a method to convert fromLst<Foo>
to List<FooFooJsonSimplifiedSerializationWrapper
> that you will have to call at some point before serializing:Main
with some tests:This code will print:
Foo serialization: {"id":1,"fooList":[{"id":2,"fooList":[]},{"id":3,"fooList":[]}]}
Bar serialization: {"fooList":[{"id":1,"fooList":[2,3]}]}
Another solution could involve using
Views
with@JsonView
annotation and customizing the views to adapt the serialization to your needs but in my opinion is a more cumbersome solution.