Search code examples
javaxstreamxml-deserialization

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 MyClass written to it using XStream.

Now MyClass has changed and polygon has been replaced with List<Polygon> and the field has been renamed to polygons, and I'm trying not to break deserialization. I want to change the deserialization of the polygon 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 MyClass?

thanks, Jeff


Solution

  • 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;
    import com.thoughtworks.xstream.io.HierarchicalStreamReader;
    import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
    
    public class MyClassConverter implements Converter{
    
        @Override
        public boolean canConvert(Class clazz) 
        {
            return clazz.equals(MyClass.class);
        }
    
        @Override
        public void marshal(Object value, HierarchicalStreamWriter writer,
                MarshallingContext context) 
        {
    
        }
    
        @Override
        public Object unmarshal(HierarchicalStreamReader reader,
                UnmarshallingContext context) 
        {
            // Create MyClass Object
            MyClass myClass = new MyClass();
    
            // Traverse Tree
            while (reader.hasMoreChildren()) 
            {
                reader.moveDown();
                if ("polygon".equals(reader.getNodeName())) 
                {
                    Polygon polygon = (Polygon)context.convertAnother(myClass, Polygon.class);
                    myClass.addPolygon(polygon);
                } 
                reader.moveUp();
            }
    
            // Return MyClass Object
            return myClass;
        }
    }
    

    In case you're unawares, here's a reference guide: http://x-stream.github.io/converter-tutorial.html

    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.