Table of Contents

How to break a reference chain error in Jackson? (StackOverflowException error)

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:

If we try to serialize these POJO with Jackson's ObjectMapper, we get a circular reference when:

Techniques

The techniques that you can use to break a circular references are:

Object Reference Identity

Through the Object Reference Identity 1), you can define your data and let Jackson handle the circular reference by:

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:

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?