2012-05-07 36 views
2

對象的Java解組名單上有XML,看起來像下面這樣:與JAXB

<?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> 

我有一個鏈表類類,如下所示:

@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: 「」,當地 「鏈表類」)。預計元素< {}對象>,< {}鏈表類>

編輯: 我只注意到我改變了我的鏈表類對象的XmlRootElement將標籤@XmlRootElement(name =「鏈表類」)一對夫婦的問題和我對象的XmlRootElement將標籤@XmlRootElement(NAME =「對象)。我不再得到的異常,但是我得到現在的對象空列表。

任何幫助深表感謝。

回答

3

很好用的,它說預期的元素:ObjectobjectList(開始用小寫字母「O」),但它讀取ObjectList(開始用大寫字母「O」)!

+0

你是對的,我已經解決了這個問題(請參閱編輯),但是,我現在得到一個空對象列表 – ferics2

+0

我認爲這將有助於您發佈更新的代碼和(更重要的)輸入XML。 – rolve

+1

我會將你的答案標記爲答案,因爲它最終會成爲一個案例問題。通過修復自定義對象XmlRootElement標記中的情況,我擺脫了這個異常。空列表還因爲我仍然在ObjectList中使用大寫字母O的XmlElement標記,當它需要小寫時 – ferics2

0

也許你應該試着將您的自定義班級名稱從Object更改爲其他一些?或者確保正確的實例的Object CE是在ObjectList

+0

我的類實際上並沒有命名爲ObjectList或Object,我只是在這個問題中用於我的示例代碼。 – ferics2