Kalyan Pradhan Kalyan Pradhan - 6 months ago 117
JSON Question

Difference between @JsonIgnore and @JsonBackReference, @JsonManagedReference

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.

Answer

Lets suppose we have

private static class Player {
    public int id;
    public Info info;
}
private static 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 static class Info {
    public int id;
    @JsonIgnore
    public Player parentPlayer;
}

and @JsonManagedReference + @JsonBackReference

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

private static 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