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

2 comments:

  1. 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
  2. Thesis writing help is a valuable service that offers assistance to graduate students struggling with the complexities of writing a thesis. This service provides expert guidance and support to students throughout the entire writing process, from research and planning to final revisions. Thesis writing help services employ experienced writers who are well-versed in academic writing and research, ensuring that students receive high-quality assistance.

    ReplyDelete

Blogroll

Popular Posts