2013-04-11 122 views
1

我正在開發一個Android項目,它使用API​​來獲取它的數據。現在首先,我不能改變API的任何東西,因爲它也用於已經啓動的iPhone應用程序。所以我必須解決這個問題。Xstream Ambigious xml標籤

我想使用XStream從API中讀取XML。一切進展順利,XStream的工作非常簡單。直到我偶然發現一個帶有ambigious標籤的API調用。這是由API返回的XML是如下:

<response> 
    <plant> 
     <Name /> 
     <Description /> 
     <KeyValues> 
      <entry> 
       <Key /> 
       <Value /> 
      </entry> 
      <entry> 
       <Key /> 
       <Value /> 
      </entry> 
      <entry> 
       <Key /> 
       <Value /> 
      </entry> 
     </KeyValues> 
     <Tasks> 
      <entry> 
       <Title /> 
       <Text /> 
      </entry> 
      <entry> 
       <Title /> 
       <Text /> 
      </entry> 
     </Tasks> 
    </plant> 
</response> 

正如你可以看到兩個標籤鍵值來作爲標記任務包含的條目標籤。我遇到的問題是我無法專門將入口標籤別名到我擁有的java類。我的工廠類如下所示:

public class Plant extends BaseModel { 
    private String Name; 
    private String Description; 

    private List<KeyValue> KeyValues; 
    private List<Task> Tasks; 
} 

其中KeyValue和Task類基本上是兩個輸入類。但是當我嘗試反序列化XML我收到以下錯誤:

com.thoughtworks.xstream.converters.ConversionException: Cannot construct java.util.Map$Entry as it does not have a no-args constructor : Cannot construct java.util.Map$Entry as it does not have a no-args constructor 
---- Debugging information ---- 
message    : Cannot construct java.util.Map$Entry as it does not have a no-args constructor 
cause-exception  : com.thoughtworks.xstream.converters.reflection.ObjectAccessException 
cause-message  : Cannot construct java.util.Map$Entry as it does not have a no-args constructor 
class    : java.util.Map$Entry 
required-type  : java.util.Map$Entry 
converter-type  : com.thoughtworks.xstream.converters.reflection.ReflectionConverter 
ath    : /response/plant/KeyValues/entry 
line number   : 1 
class[1]   : java.util.ArrayList 
converter-type[1] : com.thoughtworks.xstream.converters.collections.CollectionConverter 
class[2]   : com.example.android.stadseboeren.model.Plant 
version    : 0.0 
------------------------------- 

我得到的事實是,在一個XML使用模棱兩可的標籤是不理想的情況,但沒有什麼我可以做,現在去改變它。

有沒有人可以幫我解決這個問題?

乾杯大安

回答

2

OK,所以要成爲一個好公民,因爲我想通了,我會在這裏發佈答案。

最終我最終創建了一個額外的類,它基本上只是參賽名單的持有者。

public class KeyValues extends BaseModel { 

    @XStreamImplicit(itemFieldName="entry") 
    private ArrayList<KeyValueEntry> entries; 
} 

使用XStreamImplicit我可以將條目對象綁定到我的數組列表。

這不是最漂亮的解決方案,但它的工作原理。