1

Does jackson Handles/throws the Cyclic exception like net.sf.json.JSONException: There is a cycle in the hierarchy! thrown in json-lib when it detects the cycle in java object that is to be converted in json. If so how can we handle it.

Error thrown in json-lib is as follow

    1169 SEVERE: Servlet.service() for servlet JSONControllerServletGZIP threw exception
    1170 net.sf.json.JSONException: There is a cycle in the hierarchy!
    1171     at net.sf.json.util.CycleDetectionStrategy$StrictCycleDetectionStrategy.handleRepeatedReferenceAsArray(CycleDetectionStra
    1172     at net.sf.json.JSONArray._fromCollection(JSONArray.java:749)
    1173     at net.sf.json.JSONArray.fromObject(JSONArray.java:165)
    1174     at net.sf.json.JSONObject._processValue(JSONObject.java:2132)
    1175     at net.sf.json.JSONObject._setInternal(JSONObject.java:2177)
    1176     at net.sf.json.JSONObject.setValue(JSONObject.java:1005)
    1177     at net.sf.json.JSONObject._fromMap(JSONObject.java:886)
    1178     at net.sf.json.JSONObject.fromObject(JSONObject.java:248)

Thanks in advance.

2 Answers2

1

You want @JsonBackReference and @JsonManagedReference.

beerbajay
  • 19,652
  • 6
  • 58
  • 75
  • Thanks for reference beerbajay. I have one more concern about possible issues while converting large and complex java objects to JSON. Please advice. – Pravin Chikhale Feb 07 '12 at 03:49
0

No, Jackson does not keep track of cyclic instances, except for special case of self-reference which is caught. As suggested, currently best way to deal with this is by use of annotations, at least in cases where you have parent/child style reference.

StaxMan
  • 113,358
  • 34
  • 211
  • 239
  • Thanks. I am using Jackson for converting huge and complex Java object to JSON, it is working fine but is there any chances that issue could occur because of the large size of the object, if so we can try to handle and resolve it beforehand as it is critical to our project. Please advice. – Pravin Chikhale Feb 07 '12 at 03:46
  • Jackson only contains full document data if using Tree Model (JsonNode); otherwise operations are incremental, so memory usage should not be a problem. But it sounds like you are more worried about duplication -- if this is indeed a problem, you may need to wait for Jackson 2.0, which will add support for handling arbitrary references with identity (i.e. using Object Id for multiple references). – StaxMan Feb 07 '12 at 16:43
  • For what it is worth, Jackson 2.0 includes full support for eliminating cycles and duplication; see javadocs for `@JsonIdentityInfo` annotation for details. – StaxMan Jul 16 '12 at 17:48