When trying to serialize a POJO with Jackson's ObjectMapper, you may get this StackOverflowException error:
com.fasterxml.jackson.databind.JsonMappingException:
Infinite recursion (StackOverflowError) (through reference chain:
User["Group"]
->Group["User"]
->User["Group"]
)
This article explains to you how you can resolve it.
This error happens when you have a many-to-many relationship, for instance when:
If we try to serialize these POJO with Jackson's ObjectMapper, we get a circular reference when:
The techniques that you can use to break a circular references are:
Through the Object Reference Identity 1), you can define your data and let Jackson handle the circular reference by:
@JsonIdentityInfo is a class annotation that serializes a POJO by id, the second and next time that the same object is encountered. It does not serializing the complete object.
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id",
scope = User.class
)
public class User {
....
}
Note when @JsonIdentityReference is added, the POJO is serialized by id the first time it is encountered. Example:
@JsonIdentityReference(alwaysAsId = true)
You can annotate the property with:
If you exclude a property from the chain, you break the chain. See this article that lists all possibilities: How to exclude properties from the JSON output with Jackson?