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.
The. @JsonIgnore. annotation marks a field in a POJO to be ignored by Jackson during serialization and deserialization. Jackson ignores the field in both JSON serialization and deserialization.
The @JsonManagedReference annotation is a forward reference that includes during the serialization process whereas @JsonBackReference annotation is a backreference that omits during the serialization process.
@JsonIgnore is used at field level to mark a property or list of properties to be ignored.
@JsonIgnore is used to ignore the logical property used in serialization and deserialization. @JsonIgnore can be used at setter, getter or field.
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.
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);
@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}}
Here is main difference, because deserialization with @JsonIgnore
will just set null to the field so in our example parentPlayer will be == null.
But with @JsonManagedReference
+ @JsonBackReference
we will get Info
referance there
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With