3

I have the following XML string, and I'm trying to deserialize it to an object, but ultimate result is not correct.

The XML string is:
<Header><Sequence value=\"bbb-mySeq\"/><Session value=\"aaa-myValue\"/></Header>";

The object that I'm trying to deserialize to is:

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

}

The Sequence object is:

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

}

The deserialization code is:

    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);

When I do a toString() on the resulting object, I see:

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

As you can see, there should be no Session in Sequences. Thanks in advance for any help.

1 Answer 1

2

Change your call to addImplicitCollection:

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

Boaz

Sign up to request clarification or add additional context in comments.

1 Comment

I really wish I could give this answer more than one +1... it answered a question I had been trying to solve for hours. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.