3
我有以下XML字符串,我試圖將其反序列化到一個對象,但最終的結果是不正確的。Xstream(Java)不正確反序列化Xml字符串到對象
的XML字符串是:
<Header><Sequence value=\"bbb-mySeq\"/><Session value=\"aaa-myValue\"/></Header>";
,我試圖以反序列化對象是:
public class Header implements Serializable {
private static final long serialVersionUID = 1L;
private List<Session> sessions = new ArrayList<Session>();
private List<Sequence> sequences = new ArrayList<Sequence>();
public List<Session> getSession() {
return sessions;
}
public void setSession(Session session) {
this.sessions.add(session);
}
public List<Sequence> getSequence() {
return sequences;
}
public void setSequence(Sequence sequence) {
this.sequences.add(sequence);
}
}
序列對象是:
public class Sequence implements Serializable {
private static final long serialVersionUID = 1L;
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
反序列化代碼是:
XStream xstream = new XStream();
xstream.alias("Header", Header.class);
xstream.alias("Session", Session.class);
xstream.alias("Sequence", Sequence.class);
xstream.addImplicitCollection(Header.class, "sessions");
xstream.addImplicitCollection(Header.class, "sequences");
xstream.useAttributeFor(Session.class, "value");
xstream.useAttributeFor(Sequence.class, "value");
System.out.println("msg: " + msg);
Header result = (Header) xstream.fromXML(msg);
當我得到的對象上做一個toString()
,我看到:
Header [sessions=null, sequences=[Sequence [value=bbb-mySeq], Session [value=aaa-myValue]]]
正如你所看到的,應該有序列沒有會話。預先感謝您的幫助。
感謝波阿斯!解決了這個問題。 –
我真的希望我可以給這個答案不止一個+1 ......它回答了我一直試圖解決好幾個小時的問題。 :) – Xynariz