Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert XML to Object using JAXB

My client is using DropWizard/Jersey.

I am getting a response back in the form of xml. It looks like this:

enter image description here

I've created a file called package-info.java with following contents:

@XmlSchema(
        namespace = "http://webservices.amazon.com/AWSECommerceService/2011-08-01",
        elementFormDefault = XmlNsForm.QUALIFIED)

package com.aerstone.services.core.handlerpojos.amazon;


import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

Finally, I have a POJO which looks like this. For now I'm just trying to map the title and ASIN.

@XmlRootElement(name="ItemSearchResponse")
public class AmazonItem
{
    private String name;
    private String asin;

    public AmazonItem(){}

    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlElement(name="Title")
    public String getName()
    {
        return name;
    }
    public void setName(String name){this.name = name;}

    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlElement(name="ASIN")
    public String getAsin(){ return asin;}

    public void setAsin(String asin){ this.asin = asin; }
}

I'm using it like this:

        JAXBContext context = JAXBContext.newInstance(AmazonItem.class);
        Unmarshaller unMarshaller = context.createUnmarshaller();
        newItem = (AmazonItem) unMarshaller.unmarshal(response);

But I'm getting this error:

! javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"ItemLookupResponse"). Expected elements are <{http://webservices.amazon.com/AWSECommerceService/2011-08-01}ItemSearchResponse>
like image 537
Ethan Avatar asked Jan 25 '26 00:01

Ethan


1 Answers

You are attempting to unmarshal a document that starts with:

<ItemLookupRespons>

Instead of the XML document you have in your question that starts with:

<ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2011-08-01">

If you created your JAXB model from an XML schema where the document you are trying to unmarshal is valid then you should create your JAXBContext on the package name of the generated model, or on the ObjectFactory class that was generated to pull in all the classes for the model.

like image 102
bdoughan Avatar answered Jan 27 '26 14:01

bdoughan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!