Using XStream 1.2.2
The XML document:
<?xml version="1.0" encoding="ISO-8859-1"?>
<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" protocol="OCI" xmlns="C">
<sessionId xmlns="">192.168.1.19,299365097130,1517884537</sessionId>
<command xsi:type="AuthenticationRequest" xmlns="">
<userId>me@somewhere.com</userId>
</command>
</Document>
I'm trying to parse into to a Document
;
public class Document {
private String sessionId;
public Command command;
public Command getCommand() {
return this.command;
}
public void setCommand(Command command) {
this.command = command;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
}
Parsing code is:
XStream xstream = new XStream();
xstream.alias("Document", Document.class);
xstream.alias("sessionId", String.class);
xstream.alias("command", Command.class);
xstream.alias("userId", String.class);
Document doc = (Document) xstream.fromXML(theInput, Document.class);
but this throws:
java.lang.ClassCastException: java.lang.Class cannot be cast to com.mycompany.ocip.server.model.Document
because the returned object from fromXml
is of type: Class<com.mycompany.ocip.server.model.Document>
Shouldn't I expect it to return a com.mycompany.ocip.server.model.Document
instance?
That needs to be:
Document doc = (Document) xstream.fromXML(theInput);
If you pass in a second parameter, XStream will try to populate that with the values from the XML. Since in your code, you're passing in a class object, XStream will try to populate the class object and return it.
The JavaDoc has the details.