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>"));

3 comments:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training in India . Nowadays Java has tons of job opportunities on various vertical industry.


    or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

    ReplyDelete
  2. I want to always read your blogs. I love them Are you also searching for Nursing Pico Writing Help? we are the best solution for you. We are best known for delivering Nursing Pico writing services to students without having to break the bank

    ReplyDelete
  3. Your blogs are great.Are you also searching for Nursing Writing Services? we are the best solution for you. We are best known for delivering nursing writing services to students without having to break the bank.whatsapp us:+1-(951)-468-9855

    ReplyDelete

Blogroll

Popular Posts