Cyclic links in the bi-directional relationship of many, many

I have a bi-directional relationship in many ways in my essences. See the example below:

public class Collaboration { @JsonManagedReference("COLLABORATION_TAG") private Set<Tag> tags; } public class Tag { @JsonBackReference("COLLABORATION_TAG") private Set<Collaboration> collaborations; } 

When I try to serialize this to JSON, I get the following exception: `

"java.lang.IllegalArgumentException: unable to handle managed / backlinks" COLLABORATION_TAG ": backlink type (java.util.Set) is not compatible with the managed type (foo.Collaboration).

Actually, I know this makes sense because javadoc explicitly states that you cannot use @JsonBackReference for collections. My question is: how do I solve this problem? What I did now is removing the @JsonManagedReference annotation on the parent side and adding @JsonIgnore on the child side. Can someone tell me which side effects this approach has? Are there any other suggestions?

+8
java json jackson many-to-many
source share
2 answers

I have finished implementing the following solution.

One end of the relationship is considered the parent. He does not need the annotation associated with Jackson.

 public class Collaboration { private Set<Tag> tags; } 

The other side of the relationship is implemented as follows.

 public class Tag { @JsonSerialize(using = SimpleCollaborationSerializer.class) private Set<Collaboration> collaborations; } 

I use a custom serializer to make sure that circular references do not occur. A serializer can be implemented as follows:

 public class SimpleCollaborationSerializer extends JsonSerializer<Set<Collaboration>> { @Override public void serialize(final Set<Collaboration> collaborations, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException { final Set<SimpleCollaboration> simpleCollaborations = Sets.newHashSet(); for (final Collaboration collaboration : collaborations) { simpleCollaborations.add(new SimpleCollaboration(collaboration.getId(), collaboration.getName())); } generator.writeObject(simpleCollaborations); } static class SimpleCollaboration { private Long id; private String name; // constructors, getters/setters } } 

This serializer will only show a limited set of Collaboration entity properties. Since the "tags" property is not specified, circular links will not be executed.

A good reading of this topic can be found here . It explains all the possibilities when you have a similar scenario.

+3
source share

a very convenient implementation of the interface is provided in the jackson 2 library as

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

in maven

 <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.0.2</version> </dependency> 
+1
source share

All Articles