2013-01-04 90 views
1

將XML文件轉換爲對象時,處理空值時出現問題。反序列化xstream時出現空值

我有下面的XML輸入:

<?xml version="1.0" encoding="UTF-8" ?> 

<Results> 
<show> 
<showid>10353</showid> 
<name>Film Buff Of The Year</name> 
<link>http://www.tvrage.com/shows/id-10353</link> 
<country>UK</country> 
<started>1982</started> 
<ended>1986</ended> 
<seasons>1</seasons> 
<status>Canceled/Ended</status> 
<classification>Game Show</classification> 
<genres></genres> 
</show> 
<show> 
<showid>2930</showid> 
<name>Buffy the Vampire Slayer</name> 
<link>http://www.tvrage.com/Buffy_The_Vampire_Slayer</link> 
<country>US</country> 
<started>1997</started> 
<ended>2003</ended> 
<seasons>7</seasons> 
<status>Canceled/Ended</status> 
<classification>Scripted</classification> 
<genres><genre>Action</genre><genre>Adventure</genre><genre>Comedy</genre<genre>Drama</genre<genre>Mystery</genre><genre>Sci-Fi</genre></genres> 
</show> 
</Results> 

而且我想將其轉換成一個對象調用tvSeries,這種方式:

XStream xstream = new XStream(); 
xstream.alias("Results", TVSeries.class); 
xstream.alias("show", Show.class); 
tvSeries = (TVSeries) xstream.fromXML(file); 

其中類TVSeries.java有以下內容:

public class TVSeries { 

private ArrayList<Show> showList; 

public TVSeries(){ 
    showList = new ArrayList<>(); 
} 

public int size(){ 
    return showList.size(); 
} 

} 

and the class Show.java以下內容:

public class Show { 

private String showid, name, link, country, started, ended, seasons,status,classification; 
ArrayList<String> genres; 

public Show(){ 
    genres = new ArrayList<>(); 
} 

public Show(String showid, String name, String country, String status, String link, String started, String ended, String classification, String seasons, ArrayList<String> genres){ 
    this.showid = showid; 
    this.name = name; 
    this.country = country; 
    this.status = status; 
    this.link = link; 
    this.started = started; 
    this.ended = ended; 
    this.seasons = seasons; 
    this.classification = classification; 
    this.genres = genres; 
} 
} 

現在我遇到的問題是我的對象始終爲空。我對XStream沒有太多的經驗,所以有一點幫助會非常有用。

謝謝

+0

你嘗試過'addImplicitCollection'嗎?看看[XStream教程](http://xstream.codehaus.org/alias-tutorial.html),看看它是如何工作的。 – atomman

+0

謝謝你的建議,但它不起作用。仍然是空值。 – pixie

+0

我很好奇;你粘貼的代碼是否可以工作?我試着運行它,因爲你已經在這裏提供它,但我得到的XStream錯誤... –

回答

3

經過一些跟蹤和錯誤,我發現通過添加這些(並修復xml當然)工作。

xstream.alias("Results", TVSeries.class); 
xstream.alias("show", Show.class); 
xstream.addImplicitCollection(TVSeries.class, "showList"); 
xstream.aliasType("genre", String.class); 
使用XStream的時候,如果你發現自己在這樣的情況也經常幫助構建在Java中的測試結構,它序列化到XML只是爲了看看XML的樣子

只是一些額外的提示。

+0

非常感謝你的回答。它也適用於我。 – pixie

1

使用JAXB編組和解組你的XML數據。 並使用http://docs.oracle.com/javase/6/docs/technotes/tools/share/xjc.html使用XSD架構創建Java類:

創建MyXML類:XJC -d SRC -pcom.foo.myapp MyXML.xsd

來解讀XMLFILE到與myXML對象:

MyXML myXML = JaxbMarshalUnmarshalUtil.unmarshal(xsdFile,xmlFile,MyXML.class);

並注意:如果你沒有一個模式,你做錯了!