Custom XStream Converter

(Recovered from my old Blog).

XStream is a great utility for serializing objects to XML – and then back again.

The default XML output is neat enough – albeit a little verbose (using fully qualified class names for example). There are plenty of tutorials available showing how to use XStream aliases to clean up the output (e.g. Manual Tweaking Output).

However, sometimes it is not enough to just tweak and alias – more serious manipulation of the output stream is required. For example, complicated Collection-based objects come out very cumbersome (but generic – which is the point). Luckily, XStream provides a powerful interface for custom generation (A Converter in XStream-speak).

To fully control how an object is serialised, create a new class which implements the Converter interface:

As can be seen above, the canConvert method tells XStream which objects should use this converter. The other two methods are called when converting objects to XML (marshal) or converting XML to objects (unmarshal).

Marshalling the object is achieved by starting and ending Nodes, while populating their attributes and values. So for example:

will iterate through a collection generating the following output:

These patterns can become arbitrarily complex.

Unmarshalling is a little more complicated. XStream will work out which (registered – see later) Converter to use by matching the node to the class (in my head these seems like an extremely difficult task… I’m not sure how XStream has implemented this – maybe I should look into this!) The node (and all children) will be passed to the unmarshal method.

It is up to us to define how the target object is populated from these nodes. Methods are provided to:

Check if the node has children (reader.hasMoreChildren())
Move down to the child level (reader.moveDown())
Move back up to the parent level (reader.moveUp())
The moveUp/Down methods can be called as many times as necessary to walk the tree.

I provide a full example as I couldn’t find many good ones on the net:

Out of completeness, here is the equivalent marshal implementation:

To register the Converter simply add the following line when you instantiate the XStream object:

Leave a Reply

Your email address will not be published. Required fields are marked *