我有如下所示的 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:“”,本地:“ObjectList”)。预期元素是 <{}Object>、<{}objectList>
编辑: 我刚刚注意到几个问题我将我的 ObjectList 对象的 XmlRootElement 标记更改为 @XmlRootElement(name = "ObjectList") 并将我的对象的 XmlRootElement 标记更改为 @XmlRootElement(name = "object)。我不再得到异常,但是我现在得到并清空对象列表。
任何帮助深表感谢。