I am working with fasterxml, and I have two objects that have a relationship "one to many" or "many to one". For example the class Author and the class Book, one author has many books, and one book has one author. Can I tell fasterxml not to serialize the author of the book, only when the book is in it's author's books collection, but when the book is on itself, to serialize it.
Author class:
public class Author{
public int id;
public string name;
@JsonManagedReference
public Set<Book> books;
}
Book class:
public class Book{
public int id;
public string name;
@JsonBackReference
public Author author;
}
That setup works just fine if I want to get only the author, because the books are in place and theirs's author property isn't being serialized, but if I want to serialize only the book, it's author again isn't being serialized, because of the "@JsonBackReference" annotation. Is there any workaround in the said situation? Here are some more examples if you are not getting what I mean...
When I serialize an Autor:
{
id:3,
name: "Ivan Vazov"
books:[
{
id:5,
name: "Under the Yoke"
}
]
}
And that is what I want here.
When I serialize a Book:
{
id:5,
name: "Under the Yoke"
}
But i don't want this, I want this:
{
id:5,
name: "Under the Yoke",
author: {
id:3,
name: "Ivan Vazov"
}
}
Any thoughts on the matter would be great! Thanks.
If you want the references to be serialized from both sides(Book, Author) then jackson faces the issue with circular reference where it get's stuck in an endless loop of references when serializing one of those 2 objects.
The workaround was with @JsonManagedReference
and @JsonBackReference
where jackson ignored 1 side and serialized only the other side in order to avoid circular reference.
The solution to your problem (when you want to serialize both sides) is to create seperate DTO objects(AuthorDto, BookDto) and instead of returning from your controller a Author to be serialized you return an AuthorDto. Same with Book. Then circlular reference problem does not exist any more and both sides serialize the problematic references.