Ok, so I'm trying to test some stuffs with jackson json converter. I'm trying to simulate a graph behaviour, so these are my POJO entitieshtml
@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); } @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") public class ChildEntity implements java.io.Serializable { private String id; private String description; private ParentEntity parent; }
The tags are required in order to avoid exception on serialization. When I try to serialize an object (both on a file or on a simple string) all works fine. However, when I try to deserialize the object, it throws an exception. This is the simple test method (try/catch omitted for simplicity)java
{ 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); ObjectMapper mapper = new ObjectMapper(); File f = new File("parent_entity.json"); mapper.writeValue(f, pe); String s = mapper.writeValueAsString(pe); ParentEntity pe3 = mapper.readValue(f,ParentEntity.class); ParentEntity pe4 = mapper.readValue(s, ParentEntity.class); }
and this is the exception thrown (of course, repeated twice)json
com.fasterxml.jackson.databind.JsonMappingException: Already had POJO for id (java.lang.String) [com.fasterxml.jackson.annotation.ObjectIdGenerator$IdKey@3372bb3f] (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) [com.fasterxml.jackson.annotation.ObjectIdGenerator$IdKey@3372bb3f] ...stacktrace...
So, what is the cause of the problem? How can I fix it? Do I need some other annotation?app