Jackson - 具有双向关系的实体序列化(避免循环) [英] Jackson - serialization of entities with birectional relationships (avoiding cycles)
问题描述
我有两个实体:
Parent {
Child[] children;
}
and
Child {
Parent parent;
}
我知道 @JsonBackReference
和 @JsonManagedReference
.它们很好,如果我正在序列化 Parent
的实例.
I'm aware about @JsonBackReference
and @JsonManagedReference
.
They are good, if I'm serializing instances of Parent
.
但我还需要传输 Child
的实例,并且我想要填充 parent
字段.
But I also need to transfer instances of Child
and I want to have the parent
field populated.
换句话说:
- 在序列化
Parent
时,它应该有children
但它们的父字段可能为空(可以通过使用 json 引用注释来解决). - 在序列化
Child
时,它应该有parent
和他们的children
(但children
不必填充parent
.
- On serialization of
Parent
it should havechildren
but their parent field might be empty (can be solved by using json reference annotations). - On serialization of
Child
it should haveparent
with theirchildren
(butchildren
don't have to haveparent
populated.
有没有办法使用标准的 Jackson 功能来解决它?
Is there a way to solve it using standard Jackson capabilities?
即跳过已经序列化的实体的序列化,而不是将字段标记为符合或不符合序列化条件.
I.e. skip serialization of entities which were already serialized instead of marking fields eligible or non-eligible for serialization.
推荐答案
Jackson 2.0 确实支持完整的循环对象引用.请参阅Jackson 2.0 发布"(处理任何对象图"部分,甚至是循环的!') 为例.
Jackson 2.0 does support full cyclic object references. See "Jackson 2.0 released" (section 'Handle Any Object Graphs, even Cyclic ones!') for an example.
基本上,对于需要 id/idref 样式处理的类型,您需要使用新的 @JsonIdentityInfo
.在您的情况下,这将是 Parent
和 Child
类型(如果一个扩展另一个,只需将其添加到超类型就可以了).
Basically, you will need to use new @JsonIdentityInfo
for types that require id/idref style handling. In your case this would be both Parent
and Child
types (if one extends the other, just add it to super type and that's fine).
这篇关于Jackson - 具有双向关系的实体序列化(避免循环)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!