【问题标题】:Difference between @JsonIgnore and @JsonBackReference, @JsonManagedReference@JsonIgnore 和 @JsonBackReference、@JsonManagedReference 之间的区别
【发布时间】:2016-09-20 10:29:06
【问题描述】:

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

注意: 这些是 Jackson 注释。

【问题讨论】:

  • 是的,我已经试用了文档并在项目中实现了它,但我只是对他们在转换过程中使用的技术感到困惑。由于它们都产生了相同的结果,所以我很困惑在哪里更喜欢其中一个。
  • 解决JSON递归依赖的三种方法:springquay.blogspot.com/2016/01/…

标签: java json jackson


【解决方案1】:

假设我们有

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 进行反序列化 只会将 null 设置为该字段,因此在我们的示例中 parentPlayer 将为 == null。

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

【讨论】:

  • 非常感谢它消除了我心中的许多疑虑。我试图搜索这种特定类型的序列化,它不会破坏或忽略序列化的任何一方
  • @varren 我有一个类似的问题here 我需要解析递归字段,看起来我可能需要使用@JsonManagedReference 但不确定它会如何工作?我尝试使用JsonManagedReference 和JsonBackReference,但它似乎不起作用,每次我遇到异常,所以想看看你是否可以帮助我。
【解决方案2】:

用于解决无限递归(StackOverflowError)

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

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

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

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

【讨论】:

  • 感谢 Ali,这有助于我找出忽略、序列化和反序列化之间的真正区别。非常感谢
  • @AliDehghani 我有一个类似的问题here 我需要解析递归字段,看起来我可能需要使用@JsonManagedReference 但不确定它是如何工作的?我尝试使用JsonManagedReference 和JsonBackReference,但它似乎不起作用,每次我遇到异常,所以想看看你是否可以帮助我。
猜你喜欢
  • 2015-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-23
  • 2016-11-07
  • 2021-11-15
  • 2021-12-20
相关资源
最近更新 更多