Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

json - jackson self reference leading to cycle


I have a problem when converting hibernate objects to JSON with Jackson, because some objects have a self-reference in their definition. The problem is that I don't control the code of those entities so I cannot put annotations in there.

Actually I would like to just limit the depth of the recursivity, for example to 5 levels. I need generic code that works with any entity object that contains self reference.. Is it possible? I don't mind use another JSON library.

The following simple code

ObjectMapper mapper = new ObjectMapper();

Query q = session.createQuery("from Hazard ");
List<Hazard> hazards = q.list();

for (Hazard h : hazards) {
    String hazardJson;
    hazardJson = mapper.writeValueAsString(h);
}

Gives me exception:

org.codehaus.jackson.map.JsonMappingException: Direct self-reference leading to cycle (through reference chain: com.fgm.imsma.pojo.Hazard["location"]->com.fgm.imsma.pojo.Location["location"])
    at org.codehaus.jackson.map.ser.BeanPropertyWriter._reportSelfReference(BeanPropertyWriter.java:473)
    at org.codehaus.jackson.map.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:411)
    at org.codehaus.jackson.map.ser.BeanSerializer.serializeFields(BeanSerializer.java:245)
    at org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:212)
    at org.codehaus.jackson.map.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:428)
    at org.codehaus.jackson.map.ser.BeanSerializer.serializeFields(BeanSerializer.java:245)
    at org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:212)
    at org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:587)
    at org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:245)
    at org.codehaus.jackson.map.ObjectMapper._configAndWriteValue(ObjectMapper.java:1993)
    at org.codehaus.jackson.map.ObjectMapper.writeValueAsString(ObjectMapper.java:1595)
    at imsma.json.GetObjects.main(GetObjects.java:47)

Thanks in advance for any suggestions!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use Jackson 2.0 - it handles cyclic references (with @JsonIdentityInfo annotation)

If you cannot add annotations directly to the class then use MixIn annotations. An example here: https://github.com/FasterXML/jackson-docs/wiki/JacksonMixInAnnotations


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...