While converting XML to Java Object if XSTREAM parser found any unexpected XML then it will throw conversion exception.

POJO class :

import com.thoughtworks.xstream.annotations.XStreamAlias;

@XStreamAlias("square")
public class Square {
    @XStreamAlias("size")
    int size;

    public int getSize() {
        return size;
    }

    @Override
    public String toString() {
        return "Square [size=" + size + "]";
    }

    public void setSize(int size) {
        this.size = size;
    }

}

Expected XML structure :

As per above POJO class the ROOT element is "square" and children element is "size". The final acceptable XML structure will be  
<square>
    <size>12</size>
</square>

Un-Expected XML structure :

Here XStream don't expect the unknown tags like "width" as shown below XML. The general XStream parser will throw Conversion Exception.
<square>
    <size>12</size>
    <width>12</width>
</square>

XStream parser :

Define XStream parser like below. It will ignore all unexpected XML.
XStream xstream = new XStream() {
            @Override
            protected MapperWrapper wrapMapper(MapperWrapper next) {
                return new MapperWrapper(next) {
                    @Override
                    public boolean shouldSerializeMember(Class definedIn,
                            String fieldName) {
                        if (definedIn == Object.class) {
                            return false;
                        }
                        return super
                                .shouldSerializeMember(definedIn, fieldName);
                    }
                };
            }
        };

Libraries Required :

Usage :

xstream.processAnnotations(Square.class);
System.out.println((Square)xstream.fromXML("<square><size>12</size><width>12</width></square>"));

0 comments:

Blogroll

Follow this blog by Email

Popular Posts