2016-05-23 32 views
0

我有以下實體:- 傑克遜與自我參照序列化實體

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

假設我們有實體AB其中B.relatedRegistryEntries包含AA.relatedRegistryEntries包含B

當我嘗試序列化AB時,我得到StackOverflowError。我怎樣才能在此列表中序列化唯一的ID?

+0

也許你可以使用'@JsonIdentityInfo(發電機= ObjectIdGenerators.IntSequenceGenerator.class,財產=「ID 「)'在你的課堂上方。或者你可以在自己的List類上面編寫自定義序列化程序,並使用它'@JsonDeserialize(using = CustomDeserializer.class)'和'@ JsonSerialize'註釋列表 – varren

回答

3

傑克遜支持@JsonIdentityInfo。這就是你正在描述的內容:將這個註釋添加到一個類將使該類的所有實例都被序列化爲一個額外的ID字段,並且在下一次需要序列化同一個實例時,該ID字段的值將被寫入而不是整個對象。

但是,請注意,這不是標準的JSON。一般來說,通常使用JSON格式,因爲它被許多庫所廣泛支持。使用此功能可能會給您的API客戶端帶來額外的問題。

的兼容性更好的方法是序列化的自我引用的對象沒有它的自我參照場:

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

非常感謝! – Everv0id