xstream.fromXML返回一个Class

时间:2018-02-06 02:44:34

标签: java xstream

使用XStream 1.2.2

XML文档:

<?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>

我试图解析为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;
    }
}

解析代码是:

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

但这会引发:

  

java.lang.ClassCastException:java.lang.Class无法强制转换为com.mycompany.ocip.server.model.Document

因为fromXml返回的对象类型为:Class<com.mycompany.ocip.server.model.Document>

我不希望它返回com.mycompany.ocip.server.model.Document个实例吗?

1 个答案:

答案 0 :(得分:3)

那需要:

Document doc = (Document) xstream.fromXML(theInput);

如果传入第二个参数,XStream将尝试使用XML中的值填充该参数。因为在你的代码中,你传入一个类对象,XStream将尝试填充类对象并返回它。

JavaDoc有详细信息。