java - 如果从实体关系调用 JsonIgnore 属性

标签 java json spring jackson

我正在尝试有条件地 @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/

相关文章:

java - Spring 启动 : ClassNotFoundException when configuring maxUploadSize of CommonMultipartResolver

java - 将方法发布为 Web 服务

java - EhCache DiskStore在内存中

java - 保存与两个现有实体有关系的新实体

javascript - 如何使用javascript以逗号分隔的字符串转换json值

java - Spring Boot应用程序错误

java - 如何通过仅替换一位数字来继续查找 2 个整数的最大总和?

java - 使用Java ObjectMapper获取JSON字符串

c# - 如何使用 C# 返回序列化为 JSON

Spring Integration - 消息驱动 channel 适配器 - 转换器错误句柄、原始消息