直接自引用导致循环exception

我有类似这样的课

public abstract class ElasticSearchValue { private Long txId; private Long currentTxId; private T previous; public Long getTxId() { return txId; } public void setTxId(Long txId) { this.txId = txId; } public Long getCurrentTxId() { return currentTxId; } public void setCurrentTxId(Long currentTxId) { this.currentTxId = currentTxId; } public Object getPrevious() { return previous; } public void setPrevious(T previous) { this.previous = previous; } } 

还有一个扩展上述类的类

 public class DailyActivity extends ElasticSearchValue { Long agentId; Date date; Long success; public Long getAgentId() { return agentId; } public void setAgentId(Long agentId) { this.agentId = agentId; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public Long getSuccess() { return success; } public void setSuccess(Long success) { this.success = success; } @Override public String toString() { return agentId + "_" + date.toString(); } } 

现在,我有一个DailyActivity类型的对象,当我尝试将其转换为json字符串时,我得到以下exception:

 Caused by: com.fasterxml.jackson.databind.JsonMappingException: Direct self-reference leading to cycle (through reference chain: com.pr.analysis.DailyActivity["previous"]) 

我在google上寻找解决方案,但我得到的解决方案要求将jsonIgnore放到以前的值,这不是我打算做的。 有人遇到过同样的问题吗? 谢谢

编辑我知道课堂上有一个循环,我问如何反序列化具有自引用的类?

在这种情况下,您需要注释与@JsonManagedReference和@JsonBackReference的关系,如下所示:

  @ManyToOne @JoinColumn(name = "company_id", referencedColumnName = "id") @JsonBackReference private Company company 

  @OneToMany(mappedBy="company") @JsonManagedReference private Set employee = new HashSet(); 

这里有一个很好的例子

自我引用在这里:

 public class DailyActivity extends ElasticSearchValue { 

你说DailyActivity是一个ElasticSearchValue ,它本身就是一个ElasticSearchValue> ,这无限地继续……

更新:我会打破两个class级。 创建DailyActivity而不ElasticSearchValue

 public class DailyActivity { // the same content as your class above 

然后创建另一个类,如:

 public class ElacticDailyActivity extends ElasticSearchValue { 

尝试@JsonIdentityInfo此示例中给出的@JsonIdentityInfo注释。 更多详细信息, 请访问http://wiki.fasterxml.com/JacksonFeatureObjectIdentity

 @JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id") public class Identifiable { public int value; public Identifiable next; } 

我想你代码中的某个地方。 DailyActivity的某个实例的前一个指向自己。