3

我有以下 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()对结果对象执行 a 时,我看到:

Header [sessions=null, sequences=[Sequence [value=bbb-mySeq], Session [value=aaa-myValue]]]

如您所见,Sequences 中不应该有 Session。提前感谢您的帮助。

4

1 回答 1

2

更改对 addImplicitCollection 的调用:

xstream.addImplicitCollection(Header.class, "sessions", Session.class);
xstream.addImplicitCollection(Header.class, "sequences", Sequence.class);

波阿斯

于 2012-12-12T08:57:03.187 回答