Difference between @JsonIgnore and @JsonBackReference, @JsonManagedReference

JavaJsonJackson

Java Problem Overview


I know both @JsonIgnore and @JsonManagedReference, @JsonBackReference are used to solve the Infinite recursion (StackOverflowError), what is the difference between these two?

Note : These are Jackson annotations.

Java Solutions


Solution 1 - Java

Lets suppose we have

private class Player {
    public int id;
    public Info info;
}
private class Info {
    public int id;
    public Player parentPlayer;
}

// something like this:
Player player = new Player(1);
player.info = new Info(1, player);

Serialization

@JsonIgnore

private class Info {
    public int id;
    @JsonIgnore
    public Player parentPlayer;
}

and @JsonManagedReference + @JsonBackReference

private class Player {
    public int id;
    @JsonManagedReference
    public Info info;
}

private class Info {
    public int id;
    @JsonBackReference
    public Player parentPlayer;
}

will produce same output. And output for demo case from above is: {"id":1,"info":{"id":1}}

Deserialization

Here is main difference, because deserialization with @JsonIgnore will just set null to the field so in our example parentPlayer will be == null.

enter image description here

But with @JsonManagedReference + @JsonBackReference we will get Info referance there

enter image description here

Solution 2 - Java

> are used to solve the Infinite recursion (StackOverflowError)

@JsonIgnore is not designed to solve the Infinite Recursion problem, it just ignores the annotated property from being serialized or deserialized. But if there was a two-way linkage between fields, since @JsonIgnore ignores the annotated property, you may avoid the infinite recursion.

On the other hand, @JsonManagedReference and @JsonBackReference are designed to handle this two-way linkage between fields, one for Parent role, the other for Child role, respectively:

> For avoiding the problem, linkage is handled such that the property > annotated with @JsonManagedReference annotation is handled normally > (serialized normally, no special handling for deserialization) and the > property annotated with @JsonBackReference annotation is not > serialized; and during deserialization, its value is set to instance > that has the "managed" (forward) link.

To recap, if you don't need those properties in the serialization or deserialization process, you can use @JsonIgnore. Otherwise, using the @JsonManagedReference /@JsonBackReference pair is the way to go.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKalyan PradhanView Question on Stackoverflow
Solution 1 - JavavarrenView Answer on Stackoverflow
Solution 2 - JavaAli DehghaniView Answer on Stackoverflow