反序列化xstream时为null值

时间:2013-01-04 21:58:41

标签: java serialization null xstream

在将XML文件转换为Object时,我遇到了处理空值的问题。

我有以下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();
}

}

和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;
}
}

现在我遇到的问题是我的Object总是为空。我对XStream没有那么多经验,所以一点点帮助会非常有用。

谢谢

2 个答案:

答案 0 :(得分: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是什么样的。

答案 1 :(得分: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 );

并注意:如果你没有架构,你就错了!