Reputation: 3727
I try make a very 'abstract' method to convert any type of Object to an XML-String and vise versa using JAXB (javax.xml.bind.*
).
I get a very strange error which I don't know the meaning of.
javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"Incident"). Expected elements are (none)
I have searched for numerous solutions on google and stackoverflow, yet their solution don't seem t help. I'm facing a dead end here.
My converter method
public Object convertXmlToObject(String string, Class c) throws ConversionException {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(c.getClass());
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
InputStream stream = new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8));
Object converted = jaxbUnmarshaller.unmarshal(stream);
return converted;
} catch (JAXBException e) {
e.printStackTrace();
throw new ConversionException("Could not convert the message to an Object", e);
}
}
where I call the method
public void generateIncidentReport(Incident incident) throws RepositoryException, ConversionException {
ConversionTool conversionTool = new Converter();
String xmlMessage = conversionTool.convertObjectToXml(incident);
//...
}
My Incident class(which has al the needed annotations)
@XmlRootElement(name = "Incident")
@XmlAccessorType(XmlAccessType.FIELD)
public class Incident {
@XmlElement(name = "shipId")
private int shipID;
@XmlElement(name = "incidentType")
private String type;
@XmlElement(name = "action")
private String action;
@XmlElement(name = "centraleID")
private String centraleID;
@XmlElement(name = "Ship")
private Ship ship;
public Incident() {
}
//getters and setters
}
and last the XML String
<Incident><incidentType>Medisch noodgeval</incidentType><shipId>1234567</shipId></Incident>
Upvotes: 0
Views: 4603
Reputation: 32980
You write
JAXBContext jaxbContext = JAXBContext.newInstance(c.getClass());
with c
already being a class, therefore creating a context for java.lang.Class
. What you need is
JAXBContext jaxbContext = JAXBContext.newInstance(c);
Upvotes: 1