这是处理 json 时常见的双向关系问题。
我认为用杰克逊解决这个问题最简单的方法是使用@JsonIdentityInfo
。你只需要用这样的东西来注释你的类:
@Entity
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
public class EntityA{
...
}
@Entity
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
public class EntityB{
...
}
这样做的作用是,当之前已经序列化的实体(即父实体(EntityA))必须再次序列化以启动无限递归循环时,它将不会像往常一样序列化。
相反,它将使用您在注释中指定的属性进行序列化,即id
.
简而言之,注释允许您指定对象的替代表示形式,该表示形式仅在实体启动无限循环时使用,从而打破该循环。
按照您的示例,将导致:
[{
"id":"1",
"name": "name",
"entityB": {
"id":"2",
"something": "text"
"entityAExample": "1"
}
}]
您还可以仅注释 EntityB 而不是两个实体,这将导致:
[{
"id":"1",
"name": "name",
"entityB": {
"id":"2",
"something": "text"
"entityAExample": {
"id": "1",
"name": "name",
"entityBExample": "2"
}
}
}]
您也可以使用其他属性,尽管“id”通常工作正常。Here's http://fasterxml.github.io/jackson-annotations/javadoc/2.0.2/com/fasterxml/jackson/annotation/JsonIdentityInfo.html官方文档和wiki http://wiki.fasterxml.com/JacksonFeatureObjectIdentity.
Here's http://www.insaneprogramming.be/blog/2013/07/13/circular-dependencies-with-jackson/一篇文章更详细地解释了这一点another http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion一个展示了解决该问题的其他方法。