About
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.
Why does this error happen?
This error happens when you have a many-to-many relationship, for instance when:
- a Person has a list of Groups
- and the Group has a list of Persons.
If we try to serialize these POJO with Jackson's ObjectMapper, we get a circular reference when:
- a person that belongs to a group
- is also on the group's list of people.
Techniques
The techniques that you can use to break a circular references are:
- using Object Reference Identity to define your data (Jackson will then serialize only the id)
Object Reference Identity
Through the Object Reference Identity 1), you can define your data and let Jackson handle the circular reference by:
- writing the object Id
- in place of the whole object.
Identifier Definition with the @JsonIdentityInfo
@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)
Relation Definition with @JsonManagedReference and @JsonBackReference
You can annotate the property with:
- @JsonManagedReference: the forward part of the reference, the one that gets serialized normally.
- @JsonBackReference: the back part of the reference (omitted from serialization).
Excluding a property
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?