我有以下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);
}
}
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]]]
正如您所看到的,序列中应该没有会话。提前感谢您的帮助。
答案 0 :(得分:2)
将您的调用更改为addImplicitCollection:
xstream.addImplicitCollection(Header.class, "sessions", Session.class);
xstream.addImplicitCollection(Header.class, "sequences", Sequence.class);
波阿斯