好的,所以我试图用jackson json转换器测试一些东西。 我试图模拟图形行为,所以这些都是我的POJO实体杰克逊 - 反循环依赖关系上的反序列化失败
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class ParentEntity implements java.io.Serializable
{
private String id;
private String description;
private ParentEntity parentEntity;
private List<ParentEntity> parentEntities = new ArrayList<ParentEntity>(0);
private List<ChildEntity> children = new ArrayList<ChildEntity>(0);
// ... getters and setters
}
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class ChildEntity implements java.io.Serializable
{
private String id;
private String description;
private ParentEntity parent;
// ... getters and setters
}
的标签要求,以避免在序列化异常。 当我尝试序列化一个对象(包括一个文件或一个简单的字符串),一切正常。但是,当我尝试反序列化对象时,它会引发异常。这是简单的测试方法(试行为了简化省略/捕获)
{
// create some entities, assigning them some values
ParentEntity pe = new ParentEntity();
pe.setId("1");
pe.setDescription("first parent");
ChildEntity ce1 = new ChildEntity();
ce1.setId("1");
ce1.setDescription("first child");
ce1.setParent(pe);
ChildEntity ce2 = new ChildEntity();
ce2.setId("2");
ce2.setDescription("second child");
ce2.setParent(pe);
pe.getChildren().add(ce1);
pe.getChildren().add(ce2);
ParentEntity pe2 = new ParentEntity();
pe2.setId("2");
pe2.setDescription("second parent");
pe2.setParentEntity(pe);
pe.getParentEntities().add(pe2);
// serialization
ObjectMapper mapper = new ObjectMapper();
File f = new File("parent_entity.json");
// write to file
mapper.writeValue(f, pe);
// write to string
String s = mapper.writeValueAsString(pe);
// deserialization
// read from file
ParentEntity pe3 = mapper.readValue(f,ParentEntity.class);
// read from string
ParentEntity pe4 = mapper.readValue(s, ParentEntity.class);
}
,这是抛出的异常(当然,重复两次)
com.fasterxml.jackson.databind.JsonMappingException: Already had POJO for id (java.lang.String) [[email protected]f] (through reference chain: ParentEntity["children"]->java.util.ArrayList[0]->ChildEntity["id"])
...stacktrace...
Caused by: java.lang.IllegalStateException: Already had POJO for id (java.lang.String) [[email protected]f]
...stacktrace...
那么,什么是该问题的原因?我该如何解决它?我是否需要其他注释?
我不是为什么,但如果你改变ce1和ce2的id,将不会抛出异常 – esprittn 2014-11-02 13:19:18
是的,我会在几分钟后发布一些消息 – tigerjack89 2014-11-02 14:10:18