【问题标题】:How to unmarshall a InputStream using JAXB?如何使用 JAXB 解组 InputStream?
【发布时间】:2016-08-25 22:14:25
【问题描述】:

我在尝试以 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

我在这里没有看到什么?

【问题讨论】:

    标签: java xml rest jaxb


    【解决方案1】:

    嗯,你的代码可以

    return (Agent) jaxbUnmarshaller;
    

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

    你想要

     return (Agent) jaxbUnmarshaller.unmarshal(inputStreamReader);
    

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

    【讨论】:

      猜你喜欢
      • 2016-02-02
      • 1970-01-01
      • 1970-01-01
      • 2012-03-05
      • 2012-10-01
      • 1970-01-01
      • 2013-01-17
      相关资源
      最近更新 更多