Jeff Storey Jeff Storey - 1 year ago 93
Java Question

XStream deserialization when variable type changed

I have a java class that looks like

public class MyClass {
private final String str;
private Polygon polygon; // this polygon is a custom type of mine

I have an xml file that has an instance of
written to it using XStream.

has changed and polygon has been replaced with
and the field has been renamed to
, and I'm trying not to break deserialization. I want to change the deserialization of the
field to basically read the polygon and then just create a new list and add the single polygon to it. The list would then be the new field value.

Is it possible to change the conversion of just this one field? Or do I need to write a custom converter for the whole class


mre mre
Answer Source

So based on your comment, I believe you'll need a custom converter.

Here's an example:

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;

public class MyClassConverter implements Converter{

    public boolean canConvert(Class clazz) 
        return clazz.equals(MyClass.class);

    public void marshal(Object value, HierarchicalStreamWriter writer,
            MarshallingContext context) 


    public Object unmarshal(HierarchicalStreamReader reader,
            UnmarshallingContext context) 
        // Create MyClass Object
        MyClass myClass = new MyClass();

        // Traverse Tree
        while (reader.hasMoreChildren()) 
            if ("polygon".equals(reader.getNodeName())) 
                Polygon polygon = (Polygon)context.convertAnother(myClass, Polygon.class);

        // Return MyClass Object
        return myClass;

In case you're unawares, here's a reference guide:

Now, all that's left to do is register your converter, which I'm assuming you know how to do. Anyway, an important, although obvious thing to note is that 'addPolygon' is a method I used to populate your new list object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download