Intercepting Xstream while parsing XML

*爱你&永不变心* 提交于 2019-12-10 10:49:27

问题


Suppose I have a simple Java class like this:

public class User {

    String firstName;
    String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

}

Now, suppose I want to parse the following XML:

<user>
    <firstName>Homer</firstName>
    <lastName>Simpson</lastName>
</user>

I can do this with no problems in XStream like so:

User homer = (User) xstream.fromXML(xml);

Ok, all good so far, but here's my problem.

Suppose I have the following XML that I want to parse:

<user>
    <fullName>Homer Simpson</fullName>
</user>

How can I convert this XML into the same User object using XStream?

I'd like a way to implement some kind of callback so that when XStream parses the fullName field, I can split the string in two and manually set the first name and last name fields on the user object. Is this possible?

Note that I'm not asking how to split the string in two (that's the easy part), I want to know how to intercept the XML parsing so XStream doesn't try to reflectively set the fullName field on the User object (which obviously doesn't exist).

I looked at the converters that XStream provides but couldn't figure out how to use it for this purpose.

Any help would be appreciated.


回答1:


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



来源:https://stackoverflow.com/questions/4622863/intercepting-xstream-while-parsing-xml

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