unexpected element error while unmarshalling

六月ゝ 毕业季﹏ 提交于 2019-12-05 20:47:05
bdoughan

Part 1

Exception in thread "main" javax.xml.bind.UnmarshalException: unexpected element (uri:"http://example.com/service/response/v1", local:"WebResponse"). Expected elements are <{http://example.com/service/request/v1}WebResponse>
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:603)

The problem is the namespaces specified in the XML (response/v1 and request/v1).

<WebResponse xmlns="http://example.com/service/response/v1">

and package-info are different

@XmlSchema(namespace = "http://example.com/service/request/v1", elementFormDefault = XmlNsForm.QUALIFIED)
package com.example;

Part 2

Your current object model and mappings do not match the XML content. One way to solve this would be to introduce a Status class as answered by Ash.

Status

import javax.xml.bind.annotation.XmlElement;

public class Status {

    private long statusCode;
    private String description;

    @XmlElement(name = "StatusCode")
    public long getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(long statusCode) {
        this.statusCode = statusCode;
    }

    @XmlElement(name = "Description")
    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

}

WebResponse

import javax.xml.bind.annotation.*;

@XmlRootElement(name = "WebResponse")
public class WebResponse {

    private Status status;

    @XmlElement(name="Status")
    public Status getStatus() {
        return status;
    }

    public void setStatus(Status status) {
        this.status = status;
    }

}

Try adding a Status class, and put it between WebResponse and the fields.

I think that, since your XML elements go WebResponse -> Status -> StatusCode/Description, your WebResponse class should have only one field: a "status" of type Status. Class Status should then have the StatusCode and Description fields.

Edit: Also, I thought the @XmlElement annotations go on the fields, not the methods, but it's been a while since I've done it...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!