jackson – 使用自我引用序列化实体
我有以下实体:
@Entity @Table(name = "registry_entry") @JsonIgnoreProperties(ignoreUnknown = true) public class RegistryEntry extends GenericEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(unique = true, nullable = false) @JsonProperty("id") protected Long id; ... @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "srv_registry_entry_related_dependence", joinColumns = @JoinColumn(name = "id_reg_entry", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "id_related_reg_entry", referencedColumnName = "id")) @JsonProperty private List relatedRegistryEntries; ... }
假设我们有实体A
和B
,其中B.relatedRegistryEntries
包含A
而A.relatedRegistryEntries
包含B
当我尝试序列化A
或B
,我得到StackOverflowError
。 如何在此列表中仅序列化id?
jackson支持@JsonIdentityInfo
。 这就是您所描述的内容:将此注释添加到类中将使该类的所有实例都使用其他ID字段进行序列化,并且下次需要序列化同一实例时,将写入该ID字段的值而不是整个对象。
但请注意,这不是标准的JSON。 通常,通常使用JSON格式,因为它得到了许多库的广泛支持。 使用此function可能会为您的API客户端带来其他问题。
更普遍兼容的方法是在没有自引用字段的情况下序列化自引用对象:
public class RegistryEntry { @JsonIgnoreProperties("relatedRegistryEntries") private List relatedRegistryEntries; }
将此annotatin添加到我的class级解决了我的问题。
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "id")
我有一个自我引用的实体,jackson正在进行无限循环。 虽然有问题的财产是暂时的,但雅克森仍然试图序列化并提出问题。
- 弹簧控制器中的简单字符串作为JSON返回值
- 让Jackson将单个JSON对象解释为具有一个元素的数组
- ZonedDateTime的jackson反序列化问题
- Spring MVC中的流JSON输出
- DynamoDB JsonMarshaller无法反序列化对象列表
- 无法实例化类型的值
- java.lang.ClassNotFoundException:com.fasterxml.jackson.annotation.JsonInclude $ Value
- 在Jackson中将JsonNode序列化为非常特定的JSON格式
- 无法解析类型com.fasterxml.jackson.core.JsonGenerator。 它是从所需的.class文件间接引用的