问题描述
我知道@JsonIgnore
和@JsonManagedReference
,@JsonBackReference
都是用来解决无限递归(StackOverflowError)
代码>,这两者有什么区别?
I know both @JsonIgnore
and @JsonManagedReference
, @JsonBackReference
are used to solve the Infinite recursion (StackOverflowError)
, what is the difference between these two?
注意:这些是 Jackson 注释.
Note :These are Jackson annotations.
推荐答案
假设我们有
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}}
will produce same output. And output for demo case from above is: {"id":1,"info":{"id":1}}
这是主要区别,因为使用 @JsonIgnore
进行反序列化将只将该字段设置为 null,因此在我们的示例中 parentPlayer 将为 == null.
Here is main difference, because deserialization with @JsonIgnore
will just set null to the field so in our example parentPlayer will be == null.
但是使用 @JsonManagedReference
+ @JsonBackReference
我们将在那里获得 Info
引用
But with @JsonManagedReference
+ @JsonBackReference
we will get Info
referance there
这篇关于@JsonIgnore 和 @JsonBackReference、@JsonManagedReference 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!