Wednesday 20 July 2011

Forcing XStream to use reflection for serialization

XStream is a fantastic library for serialising objects to XML, this (very short) post explains how to force reflection on classes implementing the Externalizable interface. The code below is the typical usage of XStream to serialise an object

XStream xstream = new XStream();
System.out.println(xstream.toXML(someObject);

Unfortunately if someObject implements Externalizable then the output XML looks something like:
<com.blogspot.deplication.SomeObject>
    <boolean>true</boolean>
    <int>1234213</int>
    <int>20163</int>
    <int>0</int>
    <int>4211</int>
    <int>32321981</int>
    <int>1233</int>
    <boolean>true</boolean>
</com.blogspot.deplication.SomeObject>

To fix this, the priority of the ReflectionConverter needs to be increased as by default it is the last converter called when trying to serialise the object.
XStream xstream = new XStream();
ReflectionConverter reflectionConverter = new ReflectionConverter(
    new CachingMapper(xstream.getMapper()), xstream.getReflectionProvider());
xstream.registerConverter(reflectionConverter, XStream.PRIORITY_LOW);
System.out.println(xstream.toXML(someObject);

This code results in the more friendly XML output:

<com.blogspot.deplication.SomeObject>
    <__id>1234213</__id>
    <__tradeId>20163</__tradeId>
    <__linkedTradeId>0</__linkedTradeId>
    <__bookId>4211</__bookId>
    <__productId>32321981</__productId>
    <__eventConfigId>1233</__eventConfigId>
</com.blogspot.deplication.SomeObject>