在我的实体中,我有一个双向的多到多的关系。见下面的例子:
public class Collaboration {
@JsonManagedReference("COLLABORATION_TAG")
private Set<Tag> tags;
}
public class Tag {
@JsonBackReference("COLLABORATION_TAG")
private Set<Collaboration> collaborations;
}当我尝试将其序列化为JSON时,会得到以下异常:
"java.lang.IllegalArgumentException:无法处理托管/后退引用'COLLABORATION_TAG':反向引用类型(java.util.Set)与托管类型(foo.Collaboration)不兼容。
实际上,我知道这是有意义的,因为javadoc明确声明您不能在集合上使用@JsonBackReference。我的问题是,我应该如何处理这个问题?现在我所做的是删除父端的@JsonManagedReference注释,并在子端添加@JsonIgnore。有人能告诉我这种方法的副作用是什么吗?还有其他建议吗?
发布于 2013-02-14 15:50:20
最后,我实现了以下解决方案。
这种关系的一端被认为是父母。它不需要任何与杰克逊相关的注释。
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
}
}此序列化程序将只显示协作实体的一组有限属性。因为省略了“标记”属性,所以不会出现循环引用。
有关这一主题的良好阅读可以找到这里。它解释了所有的可能性,当你有一个类似的情况。
发布于 2015-03-07 00:45:44
在jackson 2库中提供了非常方便的接口实现,如
@Entity
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
public class Collaboration { ....在maven
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.0.2</version>
</dependency>https://stackoverflow.com/questions/13630096
复制相似问题