Intercepting Xstream conversion while parsing XML
        Posted  
        
            by 
                Shane Bell
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Shane Bell
        
        
        
        Published on 2011-01-07T05:49:58Z
        Indexed on 
            2011/01/07
            5:53 UTC
        
        
        Read the original article
        Hit count: 362
        
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.
© Stack Overflow or respective owner