I have the following xml string. I want to convert it in to a java object, to map each tag with the fields of that object. Its better that if I can introduce different field names compared to tag name. How I can do that? I am looking on JAXB but I am still confused about parts like “ns4:response” and tags within tags. Thank you in advance…
<ns4:response>
<count>1</count>
<limit>1</limit>
<offset>1</offset>
<ns3:payload xsi:type="productsPayload">
<products>
<product>
<avgRating xsi:nil="true"/>
<brand>Candie's</brand>
<description>
<longDescription>
long descriptions
</longDescription>
<shortDescription>
short description
</shortDescription>
</description>
<images>
<image>
<altText>alternate text</altText>
<height>180.0</height>
<url>
url
</url>
<width>180.0</width>
</image>
</images>
<price>
<clearancePrice xsi:nil="true"/>
<regularPrice xsi:nil="true"/>
<salePrice>28.0</salePrice>
</price>
</product>
</products>
</ns3:payload>
</ns4:response>
JAXB is the Java standard (JSR-222) for converting objects to/from XML. The following should help:
Unmarshalling from a String
You will need to wrap the
Stringin an instance ofStringReaderbefore your JAXB impl can unmarshal it.Different Field and XML Names
You can use the
@XmlElementannotation to specify what you want the name of the element to be. By default JAXB looks at properties. If you wish to base the mappings on the fields then you need to set@XmlAccessorType(XmlAccessType.FIELD).Namespaces
The
@XmlRootElementand@XmlElementannotations also allow you to specify namespace qualification where needed.For More Information