使用Rest Template交换方法将Json映射到POJO类

时间:2019-06-20 13:07:16

标签: json spring spring-boot

这是我对API的POST请求

ResponseEntity<String> result = rt.exchange(url, HttpMethod.POST, httpEntity, String.class);

我得到的答复如下

{
    "headers": {
        "Cache-Control": [
            "no-store"
        ],
        "Content-Type": [
            "application/json;charset=UTF-8"
        ],
        "Date": [
            "Thu, 20 Jun 2019 12:50:08 GMT"
        ],
        "Pragma": [
            "no-cache"
        ],
        "Server": [
            "val"
        ],
        "X-Content-Type-Options": [
            "nosniff"
        ],
        "X-Frame-Options": [
            "DENY"
        ],
        "X-Xss-Protection": [
            "1; mode=block"
        ],
        "Content-Length": [
            "331"
        ]
    },
    "body": {
        "access_token": "token_value,
        "scope": "KYC",
        "token_type": "bearer",
        "expires_in": 49900,
        "jti": "jti_val"
    },
    "statusCode": "OK",
    "statusCodeValue": 200
}

我需要提取 access_token,scope,token_type,statusCodeValue

所以我的POJO类的结构应该如何映射响应?或者如何从JSON中获取这些字段的值?

ResponseEntity<PojoClass> result = rt.exchange(url, HttpMethod.POST, httpEntity, PojoClass.class);

2 个答案:

答案 0 :(得分:0)

尝试一下:更新

 ResponseEntity<Response> response = rt.exchange(url, HttpMethod.POST, httpEntity, Response.class);

类定义:

身体类别:

public class Body implements Serializable{
    private String access_token;
    private String scope;
    private String token_type;
    private long expires_in;
    private String jti;

    //standard getters and setters

}

响应类别:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Response implements Serializable{
    private String statusCode;
    private int statusCodeValue;
    private Body body;

    //standard getters and setters

}

现在: 您应该使用它们各自的getters方法访问所需的值。 喜欢:

String token=response.getBody.getAccessToken();
String statusCode= respnse.getStatusCode();

答案 1 :(得分:0)

正文可以通过上面发布的代码段获取,并且可以使用“ response.getStatus()”来检索状态代码