REST xml answer - Jaxb - Amazon product API

2019-08-09 16:38发布

I'm currently (trying) to work with the amazon product API to search thourgh items. I have the response in XML, but i have an exception in jaxb, maybe i missed something..

Here is the XML :

XML response from Amazon

I want to extract items informations, but i'm getting some trouble.

Item class:

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

    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;
    }

    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlElement(name="FormattedPrice")
    public String getPrice()
    {
        return price;
    }
    public void setPrice(String price)
    {
        this.price = price;
    }
}

my builder :

public class AmazonItemBuilder
{
    public AmazonItemBuilder()
    {

    }

    public List<AmazonItem> build(InputStream response)
    {
        try
        {
            JAXBContext context = JAXBContext.newInstance(AmazonItem.class);
            Unmarshaller unMarshaller = context.createUnmarshaller();
            AmazonItem newItem = (AmazonItem) unMarshaller.unmarshal(response);
            System.out.println(newItem);
        }
        catch (JAXBException e)
        {
            e.printStackTrace();
        }
        return null;
    }
}

the "response" come from a URL response.openStream();

OK i forgot the error -_- javax.xml.bind.UnmarshalException: unexpected element (uri:"http://webservices.amazon.com/AWSECommerceService/2011-08-01", local:"ItemSearchResponse"). Expected elements are <{}ItemSearchResponse>

Thank you !

2条回答
Evening l夕情丶
2楼-- · 2019-08-09 16:51

I hope the top level class to covert the response to object should be "ItemSearchResponse", try creating a class with member variable "Items" which inturn will have another member object array "AmazonItem"

查看更多
不美不萌又怎样
3楼-- · 2019-08-09 17:03

It appears that the XML document is namespace qualified. You can use the package level @XmlSchema location annotation to specify the namespace qualification for the entire document. Package level annotations go on a special call called package-info that looks like the following:

package-info

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

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

For More Information

查看更多
登录 后发表回答