Jackson - 具有双向关系的实体序列化(避免循环) [英] Jackson - serialization of entities with birectional relationships (avoiding cycles)

查看:31
本文介绍了Jackson - 具有双向关系的实体序列化(避免循环)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个实体:

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.

换句话说:

  1. 在序列化 Parent 时,它应该有 children 但它们的父字段可能为空(可以通过使用 json 引用注释来解决).
  2. 在序列化 Child 时,它应该有 parent 和他们的 children(但 children 不必填充 parent.
  1. On serialization of Parent it should have children but their parent field might be empty (can be solved by using json reference annotations).
  2. On serialization of Child it should have parent with their children (but children don't have to have parent 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.在您的情况下,这将是 ParentChild 类型(如果一个扩展另一个,只需将其添加到超类型就可以了).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆