简体   繁体   English

Spring RestTemplate Response值全为null

[英]Spring RestTemplate Response values all null

Ok, the issue I am having is that I can succesfully make a post call using RestTemplate. 好吧,我遇到的问题是我可以使用RestTemplate成功进行调用。 The request completes successfully on the server side. 请求在服务器端成功完成。

However, when it goes to get set on client side the values do not get assigned properly. 但是,当它在客户端设置时,值不会被正确分配。 The first class below is the client side that should be populated by the Post call. 下面的第一个类是应该由Post调用填充的客户端。 The second class is the one that is being used by the server to send it. 第二个类是服务器用来发送它的类。

I believe my issue arises because of the JSON format that the server sends over. 我相信我的问题出现是因为服务器发送的JSON格式。 It looks something like the below. 它看起来像下面的东西。

{ "record":{"firstName":"Bill", "lastName":"Johnson", "role":6}}

Spring can not automatically map this into the Client side POJO. Spring无法自动将其映射到客户端POJO。 is there a way around this without having to change the server side code? 有没有办法解决这个问题,而无需更改服务器端代码?

Thank you. 谢谢。

EmployeeResponse response = restTemplate.postForObject(uri, request, EmployeeResponse.class );

//(Client Side)
public class EmployeeResponse {

    private String firstName;
    private String lastName;
    private int role;


    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName= firstName;
    }
    public String getLastName() {
        return longKey;
    }

    public void setLastName(String lastName) {
        this.lastName= lastName;
    }
    public int getRole() {
        return role;
    }

    public void setRole(int role) {
        this.role = role;
    }
}

//(Server-Side)
public class EmployeeResponse {

    private EmployeeRecord record;

    public String getFirstName() {
        return record.getFirstName();
    }

    public String getLastName() {
        return record.getLastName();
    }

    public int getRole() {
        return record.getRole();
    }

    public ELAActivationResponse(EmployeeRecord record) {
        this.record = record;
    }

}

This is because because the server response is wrapped with root element record and your client object doesn't, so its unable to marshal the response. 这是因为服务器响应包含根元素record而客户端对象没有,因此无法编组响应。

You need to annotate your response object class( EmployeeResponse ) with @JsonRootName(value = "record") 您需要使用@JsonRootName(value = "record")注释您的响应对象类( EmployeeResponse @JsonRootName(value = "record")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM