venerdì 22 maggio 2009

JSON / XML serialization of Hibernate POJOs

I recently had to serialize java objects to JSON format.
There are two libraries to do it:
Both have similar features, but i used the latter since serializes also to XML.

The use is pretty straightforward if you serialize standard objects, but things get a bit more complicated if your POJOs are also persistent (i use Hibernate for this).

There are two main problems:
  • transient fields do not get serialized: both XStream and Gson uses field inspection insted of getter/setter inspection; transient field are usually derived from existing field through a getter, and do not have a real field in the POJO
  • collections fields generate circular references: Hibernate collection implementations (i.e. PersistentSet, etc.) have hidden fields that shouldn't be serialized; beside polluting the serialized JSON/XML, they may lead to circular references
To avoid this problems, the POJO needs to be prepared for XStream serialization.
This means updating a real field with the value of a transient field, and substituting any Hibernate collection with the corresponding collection from the Java Collection Framework.

Let's see how to prepare a tree structure for serialization:
public void prepareForXStream()
{
// convert transient fields to fake persistent fields
this.leaf = isLeaf();

// convert Hibernate AbstractPersistentCollection to HashSet.
// this avoid circular references.
if (children != null)
{
this.children = new HashSet(children);
}

// call recursively on children
else
{
for (Node child : children)
{
child.prepareForXStream();
}
}
}
As you can see we store the calculated and transient leaf value into a real field, so it will get serialized.

We also change the set implementation of the children collection to HashSet.

Nessun commento: