XStream deserialization when variable type changed

时光总嘲笑我的痴心妄想 提交于 2019-12-24 06:48:00

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/4739228/xstream-deserialization-when-variable-type-changed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!