如何使用JAXB解组InputStream?

时间:2016-08-25 22:14:26

标签: java xml rest jaxb

尝试以XML表示法解组对象时,我收到了ClassCastException。

我的桌面客户端调用RESTful服务,该服务返回格式正确且经过验证的列表。

吐出异常的方法是:

public class DecodeXML {

    JAXBContext jaxbContext;
    Unmarshaller jaxbUnmarshaller;

    public Agent convertXmlToAgent(InputStreamReader inputStreamReader) {
    //      XStream xstream = new XStream();
    //      xstream.processAnnotations(Agent.class);
    //      xstream.processAnnotations(FtpConnection.class);
    //      xstream.processAnnotations(SmtpConnection.class);
    //      xstream.processAnnotations(SqlConnection.class);
    //
    //      return (Agent) xstream.fromXML(inputStreamReader);


        try {
            jaxbContext = JAXBContext.newInstance(Agent.class);
            jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            jaxbUnmarshaller.unmarshal(inputStreamReader);
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return (Agent) jaxbUnmarshaller;
    }
}

注释掉的部分是我之前正在实施的实现。

Agent pojo是

@XmlRootElement (name = "agent")
@XmlAccessorType(XmlAccessType.NONE)
public class Agent extends BasePojo {

    private static final long serialVersionUID = 1L;

    @XmlElement(name = "description")
    private String description;

    @XmlElement(name = "agentId")
    private String agentId;

    @XmlElement(name = "ftpConnection")
    private FtpConnection ftpConnection;

    @XmlElement(name = "smtpConnection")
    private SmtpConnection smtpConnection;

    @XmlElement(name = "sqlConnection")
    private SqlConnection sqlConnection;

    @XmlElement(name = "pollIntervall")
    private Integer pollInterval;

    @XmlElement(name = "lastExecutionDate")
    private Date lastExecutionDate;
    // getters and setters

我在这里看不到什么?

1 个答案:

答案 0 :(得分:3)

嗯,你的代码确实

return (Agent) jaxbUnmarshaller;

unmarshaller不是代理人。它是允许解析XML并生成代理的对象。

你想要

 return (Agent) jaxbUnmarshaller.unmarshal(inputStreamReader);

我注意到你没有发布异常的堆栈跟踪。这可能表明你并不认为这很重要。但那是你最大的错误。如果你仔细阅读它,你会注意到它准确地指出你的代码的哪一行是异常的原因。