Jackson - serialization of entities with birectional relationships (avoiding cycles)

心已入冬 提交于 2019-11-26 06:01:24

问题


I have two entities:

Parent {
   Child[] children;
}

and 

Child {
   Parent parent;
}

I\'m aware about @JsonBackReference and @JsonManagedReference. They are good, if I\'m serializing instances of Parent.

But I also need to transfer instances of Child and I want to have the parent field populated.

In other words:

  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.

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.


回答1:


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.

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).




回答2:


very handy interface implementation is provided in jackson 2 library as

@Entity
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
public class Parent { ....

@Entity
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
public class Child { ....

in maven

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.0.2</version>
</dependency>

@StaxMan provided a nice link to start from



来源:https://stackoverflow.com/questions/10065002/jackson-serialization-of-entities-with-birectional-relationships-avoiding-cyc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!