I have a data structure BookCollection which has a Set of Books. Each book has a reference to the BookCollection that it's in. This is a standard one-to-many relationship. It works well on server side, but then I have to send it down to the client. The app uses Jackson ObjectMapper for serialization, set up as a Spring Bean. The problem, is that you can't trivially serialize a BookCollection and Books, since there are no references in standard JSON (and I do need standard JSON).
the current solution is to put @JsonIgnore on Book.collection field, or more advanced, @JsonManagedReference on BookCollection.books and @JsonBackReference on Book.collection. However this doesn't solve all my problems, some requests ask for a Book object, and want to get its BookCollection also.
Ultimately, I am looking for some way to tell the Serializer to only include each object once. Thus, a when I get a Book, the JSON would look something like this:
{
isbn: 125412416,
title: "Introduction to JSON",
collection: {
name: "Programming Books",
books: [
{
isbn: 18723425,
title: "Java for experts"
},
{
isbn: 82472347,
title: "C# and its extensions"
},
]
}
}
While "C# and it's extensions" and "Java for experts" also have a reference to the collection object, it is not serialized since it was serialized already. Also, the collection object doesn't include the "Introduction to JSON" book, since it was already serialized.
And when I ask for a BookCollection, I get this:
{
name: "Programming Book",
books: [
{
isbn: 125412416,
title: "Introduction to JSON"
},
{
isbn: 18723425,
title: "Java for experts"
},
{
isbn: 82472347,
title: "C# and its extensions"
},
]
}
Serialize fields once
While BookCollection serializes splendily, Book is a little confusing, since the catalog now has SOME books (missing the original). Even better would be to allow to specify to serialize each field once. Let Book.collection be allowed to serialize once
Serializing a Book will look like this:
{
isbn: 125412416,
title: "Introduction to JSON",
collection: {
name: "Programming Books",
books: [
{
isbn: 18723425,
title: "Java for experts"
},
{
isbn: 82472347,
title: "C# and its extensions"
},
{
isbn: 125412416,
title: "Introduction to JSON"
}
]
}
}
And serializng a book collection is similar:
{
name: "Programming Book",
books: [
{
isbn: 125412416,
title: "Introduction to JSON"
},
{
isbn: 18723425,
title: "Java for experts"
},
{
isbn: 82472347,
title: "C# and its extensions"
},
]
}