我最终实现了以下解决方案。
关系的一端被视为父母。它不需要任何与Jackson相关的注释。
public class Collaboration { private Set<Tag> tags;}关系的另一端实现如下。
public class Tag { @JsonSerialize(using = SimpleCollaborationSerializer.class) private Set<Collaboration> collaborations;}我正在使用自定义序列化程序来确保不会发生循环引用。序列化器可以这样实现:
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 }}该序列化器将仅显示Collaboration实体的一组有限属性。因为省略了“标签”属性,所以不会发生循环引用。
可以在这里找到有关此主题的很好的阅读。它说明了遇到类似情况时的所有可能性。



