JAXB UnmarshallException意外元素但是"预期元素是(无)"

时间:2015-11-11 20:40:53

标签: java xml binding jaxb unmarshalling

我尝试制作一个非常抽象的'使用JAXB(javax.xml.bind.*)将任何类型的Object转换为XML-String的方法,反之亦然。 我得到一个非常奇怪的错误,我不知道其中的含义。

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"Incident"). Expected elements are (none)

我在google和stackoverflow上搜索了很多解决方案,但他们的解决方案似乎没什么帮助。我在这里面临死胡同。

我的转化方法

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

我称之为方法

public void generateIncidentReport(Incident incident) throws RepositoryException, ConversionException { 
    ConversionTool conversionTool = new Converter();
    String xmlMessage = conversionTool.convertObjectToXml(incident);
    //...
}

我的事件类(其中包含所需的注释)

@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
}

并持续 XML字符串

<Incident><incidentType>Medisch noodgeval</incidentType><shipId>1234567</shipId></Incident>

1 个答案:

答案 0 :(得分:1)

你写

JAXBContext jaxbContext = JAXBContext.newInstance(c.getClass());

c已经是一个类,因此为java.lang.Class创建了一个上下文。你需要的是

JAXBContext jaxbContext = JAXBContext.newInstance(c);
相关问题