2

我有如下所示的 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)。我不再得到异常,但是我现在得到并清空对象列表。

任何帮助深表感谢。

4

2 回答 2

3

好吧,它说的是预期元素:ObjectobjectList(以小写“o”开头),但它读取的是ObjectList(以大写“O”开头)!

于 2012-05-07T16:04:25.590 回答
0

也许您应该尝试将自定义类的名称更改为其他名称Object?或确保ObjectObjectList课堂上使用正确的实例

于 2012-05-07T15:48:33.663 回答