gtludwig gtludwig - 1 month ago 7x
reST (reStructuredText) Question

How to unmarshall a InputStream using JAXB?

I'm getting a ClassCastException when trying to unmarshall an object in a XML notation.

My desktop client calls for a RESTful service that returns the properly formatted and validated list.

The method that spits out the exception is:

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();
} catch (JAXBException e) {
// TODO Auto-generated catch block

return (Agent) jaxbUnmarshaller;

The commented out section is the former implementation I'm moving from.

pojo is

@XmlRootElement (name = "agent")
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

What am I not seeing here?


Well, your code does

return (Agent) jaxbUnmarshaller;

The unmarshaller is not an Agent. It's the object that allows parsing the XML and generating an Agent.

You want

 return (Agent) jaxbUnmarshaller.unmarshal(inputStreamReader);

I notice that you didn't post the stack trace of the exception. That's probably a sign that you didn't consider it important. But that's your biggest mistake. If you read it carefully, you'd notice that it precisely indicates which line of your code is the cause of the exception.