JAXBContext - ClassCastException



I was recently working with REST like APIs (e.g. text/xml content type response from a web request). In order to consume or use the response i need to parse the xml response .We usually use an ordinary STaX (SAX Vs. STAX) parser because it performs really well and we usually parse really huge XML files that contains thousands of elements. In the API that i am consuming the XML is really small about ~10 elements. So i decided to use JAXB (comes standard with Java 1.6) because XML is really small and I have to display the result of the service to a UI. After creating my javabeans (javabeans) and annotating it with JAXB. I initialized my jaxbContext this way (Code 1.1) and tried unmarshalling an xml. As you notice below i have the same root element for Foo and Bar xml . This is causing the JAXBContext to parse the Foo xml to a Bar class that is why i get a ClassCastException. I have to change the root elements for the xml and the JAXB @XMLRootElement annotation as well so that i  don't get the ClassCastException. I think this could also be addressed by using namespaces (I will try it one day. )


Code 1.1

try {
jaxbContext = JAXBContext.newInstance(Foo.class, Bar.class);
        Foo foo1= (Foo) jaxbContext.createUnmarshaller().unmarshal(new File("Foo.xml"));

 } catch (JAXBException e) {
log.debug(e);
 }

Foo and Bar Sample Annotated Java Code and XML


Foo.java

@XmlRootElement(name="response")
// Changed this to foo_response @XmlRootElement(name="foo_response")
@XmlAccessorType(XmlAccessType.FIELD)
public class Foo{

@XmlElement
private String foo_data_1;

       @XmlElement
private String foo_data_2;

    //...getter setters..



}


Bar.java

@XmlRootElement(name="response")
// Changed this to foo_response @XmlRootElement(name="bar_response")
@XmlAccessorType(XmlAccessType.FIELD)
public class Foo{

@XmlElement
private String bar_data_1;

       @XmlElement
private String bar_data_2;

    //...getter setters..



}


Initial Sample Foo.xml

<response> 
<foo_data_1>foo</foo_data_1>
<foo_data_2>foo 2</foo_data_2>
</response>


<foo_response> 
<foo_data_1>foo</foo_data_1>
<foo_data_2>foo 2</foo_data_2>
</foo_response>



Initial Sample  Bar.xml

<response> 
<bar_data_1>bar</bar_data_1>
<bar_data_2>bar 2</bar_data_2>
</response>


<bar_response> 
<bar_data_1>bar</bar_data_1>
<bar_data_2>bar 2</bar_data_2>
</bar_response>






Comments

Popular posts from this blog

OAuth 1.0a Request Signing and Verification - HMAC-SHA1 - HMAC-SHA256

Spark DataFrame - Array[ByteBuffer] - IllegalAurmentException

Gensim Doc2Vec on Spark - a quest to get the right Vector