@JsonIgnore和@JsonBackReference,@ JsonManagedReference之间的区别

我知道@JsonIgnore@JsonManagedReference@JsonBackReference用于解决Infinite recursion (StackOverflowError) ,这两者有什么区别?

注意:这些是Jackson注释。

让我们假设我们有

 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; } 

@JsonManagedReference + @JsonBackReference

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

会产生相同的输出。 上面的演示案例的输出是: {"id":1,"info":{"id":1}}

反序列化

这是主要区别,因为使用@JsonIgnore反序列化@JsonIgnore将null设置为字段,因此在我们的示例中,parentPlayer将为== null。

在此处输入图像描述

但是使用@JsonManagedReference + @JsonBackReference我们将在那里获得Info @JsonBackReference

在此处输入图像描述

用于解决无限递归(StackOverflowError)

@JsonIgnore不是为解决无限递归问题而设计的,它只是忽略了被序列化或反序列化的带注释属性。 但是如果字段之间存在双向链接,则由于@JsonIgnore忽略了带注释的属性,因此可以避免无限递归。

另一方面, @JsonManagedReference@JsonBackReference用于处理字段之间的这种双向链接,一个用于Parent角色,另一个用于Child角色:

为了避免这个问题,处理链接使得使用@JsonManagedReference注释注释的属性得到正常处理(正常序列化,没有特殊的反序列化处理),并且使用@JsonBackReference注释注释的属性不是序列化的; 在反序列化期间,其值设置为具有“托管”(转发)链接的实例。

回顾一下,如果在序列化或反序列化过程中不需要这些属性,则可以使用@JsonIgnore 。 否则,使用@JsonManagedReference / @JsonBackReference对是@JsonBackReference的方法。