Difference between @JsonIgnore and @JsonBackReference, @JsonManagedReference

Solution 1:

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:

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.