我在将XML响应从服务转换为POJO时遇到异常。 XML看起来像这样:
这是我的XML response。
javax.xml.bind.UnmarshalException: unexpected element (uri:""
, local:"ItemSearchResponse"). Expected elements are
<{http://webservices.amazon.com/AWSECommerceService/2011-08-01}ItemSearchResponse>
我正在使用它:
Document response = getResponse(url);
JAXBContext context = JAXBContext.newInstance(AmazonItem.class);
Unmarshaller unMarshaller = context.createUnmarshaller();
newItem = (AmazonItem) unMarshaller.unmarshal(response);
以下是我的文件的详细信息
package-info.java
@XmlSchema(
namespace = "http://webservices.amazon.com/AWSECommerceService/2011-08-01",
elementFormDefault = XmlNsForm.QUALIFIED)
package com.services.amazon;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
AmazonItem.java
@XmlRootElement(name="ItemSearchResponse")
@XmlAccessorType(XmlAccessType.FIELD)
public class AmazonItem
{
@XmlElement(name="Items")
private Items items = null;
}
Items.java
@XmlAccessorType(XmlAccessType.FIELD)
public class Items {
@XmlElement(name="Item")
List<Item> items = new ArrayList();
}
Item.java
@XmlAccessorType(XmlAccessType.FIELD)
public class Item {
@XmlElement(name="ASIN")
private String asin;
@XmlElement(name="ItemAttributes")
private ItemAttributes attributes;
@XmlElement(name="ItemLinks")
private List<ItemLinks> itemLinks;
}
ItemAttributes.java
@XmlAccessorType(XmlAccessType.FIELD)
public class ItemAttributes {
@XmlElement(name="Title")
private String title;
@XmlElement(name="Actor")
private List<String> actor;
@XmlElement(name="ProductGroup")
private String productGroup;
}
ItemLink.java
@XmlAccessorType(XmlAccessType.FIELD)
public class ItemLink {
@XmlElement(name="Description")
private String description;
@XmlElement(name="URL")
private String url;
}
ItemLinks.java
@XmlAccessorType(XmlAccessType.FIELD)
public class ItemLinks {
@XmlElement(name="ItemLink")
List<ItemLink> itemLinks;
}
答案 0 :(得分:6)
错误消息表明您正在获取如下所示的XML文档:
<ItemSearchResponse>
而不是像以下那样匹配您已映射的命名空间限定:
<ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2011-08-01">
答案 1 :(得分:4)
解释是here: JAXBContext实例初始化为使用作为参数传递的类(s)和可从这些类静态访问的类。
使用包初始化JAXBContext
,因此它可以看到在package-info.java中声明的@XmlSchema
:
JAXBContext.newInstance("com.services.amazon")
答案 2 :(得分:2)
如果您在getResponse方法中使用DocumentBuilderFactory,请尝试设置命名空间感知:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
我有相同的UnmarshalException,这解决了它。
答案 3 :(得分:1)
从package-info.java
删除命名空间并更改
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED
到
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.UNQUALIFIED.
答案 4 :(得分:0)
从package-info.java中删除名称空间 对我来说有用
例如:
@javax.xml.bind.annotation.XmlSchema(namespace = "", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)