杰克逊 - 使用自我引用序列化实体 [英] Jackson - Serialize entity with self-reference

查看:103
本文介绍了杰克逊 - 使用自我引用序列化实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下实体:

@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<RegistryEntry> relatedRegistryEntries;
  ...
}

假设我们有实体 A B 其中 B.relatedRegistryEntries 包含 A A.relatedRegistryEntries 包含 B

Assume that we have entities A and B where B.relatedRegistryEntries contains A and A.relatedRegistryEntries contains B.

当我尝试序列化 A B 时,我得到 StackOverflowError 。如何在此列表中仅序列化id?

When i try to serialize A or B, i get StackOverflowError. How can i serialize only id in this list?

推荐答案

杰克逊支持 @JsonIdentityInfo 。这就是您所描述的内容:将此注释添加到类中将使该类的所有实例都使用其他ID字段进行序列化,并且下次需要序列化同一实例时,将写入该ID字段的值而不是整个对象。

Jackson supports @JsonIdentityInfo. This is does what you're describing: adding this annotation to a class will make all instances of that class be serialized with an additional ID field, and the next time the same instance needs to be serialized the value of that ID field will be written instead of the whole object.

但请注意,这不是标准的JSON。通常,通常使用JSON格式,因为它得到了许多库的广泛支持。使用此功能可能会为您的API客户端带来其他问题。

However, note that this is not standard JSON. In general, JSON format is usually used because it's widely supported by many libraries. Using this feature will likely create additional problems for your API clients.

更普遍兼容的方法是在没有自引用字段的情况下序列化自引用对象:

The more universally compatible approach is to serialize the self-referenced object without its self-reference field:

public class RegistryEntry {
        @JsonIgnoreProperties("relatedRegistryEntries")
        private List<RegistryEntry> relatedRegistryEntries;
}

这篇关于杰克逊 - 使用自我引用序列化实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆