杰克逊 - 具有双向关系的实体的序列化(避免周期) [英] Jackson - serialization of entities with birectional relationships (avoiding cycles)
问题描述
我有两个实体:
Parent {
Child[] children;
}
and
Child {
Parent parent;
}
我知道 @JsonBackReference
和 @JsonManagedReference
。
他们很好,如果我正在序列化父
的实例。
但我还需要传输 Child
的实例,我希望填充 parent
字段。
But I also need to transfer instances of Child
and I want to have the parent
field populated.
换句话说:
- 序列化
父
它应该有children
但是它们的父字段可能是空的(可以通过使用json引用注释来解决)。 - 在序列化
子
时,它应该有父
及其子女
(但儿童
不必填充父
。
- 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支持完整的循环对象引用。请参阅< a href =http://www.cowtowncoder.com/blog/archives/2012/03/entry_466.html\"rel =noreferrer> Jackson 2.0发布(处理任何对象图,即使是Cyclic那些!')举个例子。
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).
这篇关于杰克逊 - 具有双向关系的实体的序列化(避免周期)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!