使用泛型时,RestClient不会返回完全未编组的对象

时间:2014-05-12 11:47:24

标签: java rest spring-mvc jaxb

我正在进行如下所示的RESTful WS调用:

ResponseEntity<ResponseHolder> responseEntity =
                restTemplate.exchange(url, HttpMethod.GET, requestEntity, ResponseHolder.class, 300788);

但是,在返回时我检查responseEntity中的值,它是ElementNsImpl对象而不是我嵌入到ResponseHolder中的Employee对象。 因此,条件(responseEntity.getBody().getResponse() instanceof Employee)被评估为假!


以下是我的服务器端控制器方法:

@RequestMapping(value = "/{empId}", method = RequestMethod.GET)
    public @ResponseBody ResponseHolder getEmployee(@PathVariable int empId) {
        System.out.println("Returning employee details for empId = " + empId);
        Employee employee = new Employee(123, "Akshay", "A", "Technology", 500000);

        ResponseHolder<Employee> responseHolder = new ResponseHolder<Employee>(employee, null);

        return responseHolder;
    }

以下是我ResponseHolder.java班的代码:

import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;

@XmlRootElement(name = "response")
@XmlSeeAlso(Employee.class)
public class ResponseHolder<T> {

    private T response;
    private ErrorStatus errorStatus;

    public ResponseHolder() {
    }

    public ResponseHolder(T response, ErrorStatus errorStatus) {
        this.response = response;
        this.errorStatus = errorStatus;
    }

    public T getResponse() {
        return response;
    }

    @XmlAnyElement
    public void setResponse(T response) {
        this.response = response;
    }

    public ErrorStatus getErrorStatus() {
        return errorStatus;
    }

    @XmlElement
    public void setErrorStatus(ErrorStatus errorStatus) {
        this.errorStatus = errorStatus;
    }
}

我究竟做错了什么?

感谢。

1 个答案:

答案 0 :(得分:0)

您的回复不是员工,而是员工的序列化(字符串)。您必须在客户端对数据进行重新排序,然后填写员工对象。