Note that there are some explanatory texts on larger screens.

plurals
  1. POJAXB unmarshalling with java generics
    text
    copied!<p>I am trying to unmarshall an XML document from a legacy system using JAXB. I have an xml structure as follows :</p> <pre class="lang-xml prettyprint-override"><code>&lt;response&gt; &lt;id&gt;000000&lt;/id&gt; &lt;results&gt; &lt;result&gt; &lt;!-- Request specific xml content --&gt; &lt;year&gt;2003&lt;/year&gt; &lt;title&gt;Lorem Ipsum&lt;/title&gt; &lt;items&gt; &lt;item&gt;I1&lt;/item&gt; &lt;item&gt;I2&lt;/item&gt; &lt;/items&gt; &lt;/result&gt; &lt;result&gt; &lt;year&gt;2007&lt;/year&gt; &lt;title&gt;Dolor sit amet&lt;/title&gt; &lt;items&gt; &lt;item&gt;K1&lt;/item&gt; &lt;item&gt;K2&lt;/item&gt; &lt;/items&gt; &lt;/result&gt; &lt;/results&gt; &lt;/response&gt; </code></pre> <p>The tags inside the part specified by <code>&lt;result></code> tag will change depending on my request. Since the content may change I decided to use generics for result items and I have prepared my java beans with annotations as following:</p> <pre class="lang-java prettyprint-override"><code>// imports here @XmlRootElement(name="response") @XmlAccessorType(XmlAccessType.FIELD) public class XResponse&lt;T&gt;{ private String id; @XmlElementWrapper(name="results") @XmlElement(name="result") private List&lt;T&gt; results; // setters and getters } ... @XmlRootElement(name="result") @XmlAccessorType(XmlAccessType.FIELD) public class X1Result{ private String year; private String title; @XmlElementWrapper(name="items") @XmlElement(name="item") private List&lt;String&gt; items; // setters and getters } ... </code></pre> <p>I tried unmarshalling the xml document via the code below:</p> <pre class="lang-java prettyprint-override"><code>JAXBContext context = JAXBContext.newInstance(XResponse.class, X1Result.class); Unmarshaller um = context.createUnmarshaller(); XResponse&lt;X1Result&gt; response = (XResponse&lt;X1Result&gt;) um.unmarshal( xmlContent ); List&lt;X1Result&gt; results = unmarshal.getResults(); for (X1Result object : results) { System.out.println(object.getClass()); } </code></pre> <p>I have a problem during the unmarshalling that it can't cast the list items into <code>X1Result</code> class. Instead it uses <code>org.apache.xerces.dom.ElementNSImpl</code>. </p> <p>What should I do to make JAXB Unmarshaller use <code>X1Result</code> class?</p> <p>Thanks in advance</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload