gpt4 book ai didi

java - @JsonIgnore 和 @JsonBackReference、@JsonManagedReference 之间的区别

转载 作者:IT老高 更新时间:2023-10-28 12:47:25 28 4
gpt4 key购买 nike

我知道@JsonIgnore@JsonManagedReference@JsonBackReference都是用来解决无限递归(StackOverflowError)的 code>,这两者有什么区别?

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

enter image description here

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

enter image description here

关于java - @JsonIgnore 和 @JsonBackReference、@JsonManagedReference 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37392733/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com