Intercepting Xstream while parsing XML

99封情书 提交于 2019-12-06 14:17:21
mre

You need a custom converter:

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 UserConverter implements Converter
{

    @Override
    public boolean canConvert(Class clazz) {
        return clazz.equals(User.class);
    }

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

    }

    @Override
    public Object unmarshal(HierarchicalStreamReader reader,
            UnmarshallingContext context) 
    {
        User user = new User();

        reader.moveDown();
        if ("fullName".equals(reader.getNodeName()))
        {
            String[] name = reader.getValue().split("\\s");
            user.setFirstName(name[0]);
            user.setLastName(name[1]);
        }
        reader.moveUp();

        return user;
    }
}

Reference: http://x-stream.github.io/converter-tutorial.html

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