Spring Rest操作将响应转换为类

时间:2016-01-27 18:48:08

标签: java json spring rest spring-mvc

这是我的休息电话:

RestOperations operations;
UserIdentifier resourceResponse = operations.postForObject("...", entity, UserIdentifier.class);

UserIdentifier类:

public class UserIdentifier {
    private String uid;
    private String code;
    private String retailId;

    public UserIdentifier() {

    }

    public UserIdentifier(String uid, String code, String retailId) {
        this.uid = uid;
        this.code = code;
        this.retailId = retailId;
    }

    public String getuid() {
        return uid;
    }

    public void setuid(String uid) {
        this.uid = uid;
    }

    public String getcode() {
        return code;
    }

    public void setcode(String code) {
        this.code = code;
    }

    public String getretailId() {
        return retailId;
    }

    public void setretailId(String retailId) {
        this.retailId = retailId;
    }
}

JSON回复:

{
  "userIdentifier": {
    "uid": "ee63a52cda7bf411dd8603ac196951aa77",
    "code": "63a5297e7bf411dd8603ac196951aa77",
    "retailId": "860658787",
    "pointOfEntry": "RETAIL"
  },
  "resultCode": true
}

但问题是当我运行此代码时,它会创建resourceResponse,但所有字段都是空的。知道问题是什么吗?

编辑1:我收到了正确的json响应,我只是无法将其放入java类对象中。

1 个答案:

答案 0 :(得分:2)

未能使用class转换回复。根据您的response json,您的投射对象应如下所示

class Response {
    UserIdentifier userIdentifier;
    boolean resultCode;
    ...
}

并且打电话

Response response = operations.postForObject("...", entity, Response.class);
response.userIdentifier...   // it is your data