Shane Bell Shane Bell - 3 months ago 14
Java Question

Intercepting Xstream while parsing XML

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.

mre mre
Answer

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

Comments