我正在尝试有条件地 @JsonIgnore
实体中的某些字段,如果它们是从另一个实体的集合中序列化的(多对一)。
我已尝试将 @JsonIgnoreProperties
添加到集合中,但据我所知,注释并非用于此目的。
class A {
//some fields
@ManyToOne private B b; //if only A is requested, this should NOT be ignored
}
class B {
//some fields
@OneToMany
@IgnorePrivateBInAToAvoidStackOverflow
private Set<A> collectionOfAs;
}
有什么办法可以实现这种行为吗?
最佳答案
为避免循环引用无限递归(stackoverflow 错误),您必须使用 @JsonIdentityInfo 注释 calss
所以你的课看起来像:
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
class A {
//some fields
//Integer id;
@OneToMany private B b; //if only A is requested, this should NOT be ignored
}
B 类双向使用同样的事情:
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
class B {
//some fields
@ManyToOne
@IgnorePrivateBInAToAvoidStackOverflow
private Set<A> collectionOfAs;
}
请注意,属性
指的是您的唯一字段名称(在此示例中设置为 id
)
有关更多阅读,请参阅此 article
关于java - 如果从实体关系调用 JsonIgnore 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54341468/