SAXException2: A cycle is detected in the object graph. SOLVED.

Introduction

I am writing REST web-service using jersey, jetty (as a server), EclipseLink, Guice and some test libraries, jersey provides automatic (de)serialization. During some of the GET calls, server is retrieving object from database and returns serialized json or xml string.
When I faced „A cycle is detected…” exception i spent a lot of time to find the solution. Finally i found it, but I don’t remember where anymore.


Problem

If you have cycle in reference connection between classes, you have a problem. It is simply impossible to serialize object of class which has such cycle.
If such situation occurs you will have an exception thrown during serialization. Console should throw such message:

May 23, 2013 1:58:55 PM com.sun.jersey.spi.container.ContainerResponse logException
SEVERE: Mapped exception to response: 500 (Internal Server Error)
javax.ws.rs.WebApplicationException: javax.xml.bind.MarshalException
 - with linked exception:
[com.sun.istack.SAXException2: A cycle is detected in the object graph. This will cause infinitely deep XML: ...


Solution – transient reference

(transient prevents field in class from being serialized.)
 
This can be resolved by not serializing one of those references that causes cycle. As you can expect in java, you should make transient one of those references. In fact there is such thing in JAXB, there is an annotation:
@XmlTransient, but WARNING! this is not enough, you need to also annotate class with @XmlAccessorType(value = XmlAccessType.FIELD)
 
Code should look like this:

...

@XmlRootElement
@XmlAccessorType(value = XmlAccessType.FIELD)
public class Account {

...
    @XmlTransient
    private List<Record> records = new ArrayList<Record>();

...


Important links


Reklamy

Skomentuj

Wprowadź swoje dane lub kliknij jedną z tych ikon, aby się zalogować:

Logo WordPress.com

Komentujesz korzystając z konta WordPress.com. Wyloguj / Zmień )

Zdjęcie z Twittera

Komentujesz korzystając z konta Twitter. Wyloguj / Zmień )

Zdjęcie na Facebooku

Komentujesz korzystając z konta Facebook. Wyloguj / Zmień )

Zdjęcie na Google+

Komentujesz korzystając z konta Google+. Wyloguj / Zmień )

Connecting to %s