我的XML如下所示:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ObjectList>
<object attributeOne="somedate" attributeTwo="false" attributeThree="id" attributeFour="true"/>
<object attributeOne="somedate" attributeTwo="false" attributeThree="id" attributeFour="true"/>
<object attributeOne="somedate" attributeTwo="false" attributeThree="id" attributeFour="true"/>
<object attributeOne="somedate" attributeTwo="false" attributeThree="id" attributeFour="true"/>
<object attributeOne="somedate" attributeTwo="false" attributeThree="id" attributeFour="true"/>
</ObjectList>
我有一个ObjectList类,如下所示:
@XmlRootElement
public class ObjectList {
@XmlElementWrapper(name = "ObjectList")
@XmlElement(name = "Object")
private ArrayList<Object> ObjectList;
public ArrayList<Object> getObjectList() {
return ObjectList;
}
public void setObjectList(ArrayList<Object> objectList) {
ObjectList = objectList;
}
}
一个看起来像这样的对象类:
@XmlRootElement(name = "Object")
public class Object {
Date attributeOne;
boolean attritbuteTwo;
String attributeThree;
boolean attributeFour;
@XmlAttribute
public Date getAttributeOne() {
return attributeOne;
}
public void setAttributeOne(Date attributeOne) {
this.attributeOne = attributeOne;
}
@XmlAttribute
public boolean isAttributeTwo() {
return attritbuteTwo;
}
public void setAttributeTwo(boolean attritbuteTwo) {
this.AttributeTwo = AttributeTwo;
}
@XmlAttribute
public String getAttributeThree() {
return attributeThree;
}
public void setAttributeThree(String attributeThree) {
this.attributeThree = attributeThree;
}
@XmlAttribute
public boolean isAttributeFour() {
return attributeFour;
}
public void setAttributeFour(boolean attributeFour) {
this.attributeFour = attributeFour;
}
}
当我尝试使用此代码将xml解组为对象时:
JAXBContext jaxbContext = JAXBContext.newInstance(ObjectList.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
RESTResponse response = getObjects();
ObjectList objects = (ObjectList) unmarshaller.unmarshal(new StringReader(response.getResponseBody()));
我收到以下错误:
javax.xml.bind.UnmarshalException:意外元素(uri:“”,local:“ObjectList”)。预期元素是&lt; {} Object&gt;,&lt; {} objectList&gt;
修改 我刚注意到一些问题我将我的ObjectList对象的XmlRootElement标记更改为@XmlRootElement(name =“ObjectList”),并将我的Object的XmlRootElement标记更改为@XmlRootElement(name =“object)。我不再获得异常,但是我现在得到并清空对象列表。
非常感谢任何帮助。
答案 0 :(得分:3)
好吧,它说预期元素:Object
或objectList
(以小写“o”开头)但它读取ObjectList
(以大写“O”开头)!< / p>
答案 1 :(得分:0)
也许您应该尝试将自定义类的名称从Object
更改为其他名称?或者确保在Object
类
ObjectList
的正确实例