首页 > 解决方案 > 如何在 Spring Boot 中获取 ResponseEntity 的值?

问题描述

我是 Spring Boot 的新手。我从 Spring Boot 中的 responseEntity 得到 API 的响应。我返回了响应值。但我想定义一个数组/json并将响应值设置为此数组/json。在那之后,我想得到这个数组的具体值。例如;

返回值:

{"id":"123456789","license":"6688","code":"D8B1H832EE45"}

我只想取 id 的值 123456789。

就像是;

数组['id']

我该怎么做?请帮帮我。

@GetMapping("/test")
public ResponseEntity<String> getmc() {

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("Authorization", "Bearer " + restTemplate.getAccessToken());

    HttpEntity<String> entity = new HttpEntity<>(null, headers);

    ResponseEntity x = restTemplate.exchange("https://api.x.com/v1/demo", HttpMethod.GET, entity, String.class);

    return restTemplate.exchange("https://api.x.com/v1/demo", HttpMethod.GET, entity, String.class);
}

我知道这是错的,但我只想要这样的东西:x.getBody('id');

结果:123456789

标签: apispring-bootoauth-2.0httpresponseresttemplate

解决方案


您可以基于 json 为 Pojo(普通旧 java 对象)建模,如下所示:

public class Pojo {
    private String id;
    private int license;
    private String code;

    public String getId() { return this.id;}
    public String getLicense() { return this.license;}
    public String getCode() { return this.code;}
}

然后将您的端点更改为以下签名:

@GetMapping("/test")
public ResponseEntity<String> getmc() {

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("Authorization", "Bearer " + restTemplate.getAccessToken());

    HttpEntity<Pojo> entity = new HttpEntity<>(null, headers);

    ResponseEntity x = restTemplate.exchange("https://api.x.com/v1/demo", HttpMethod.GET, entity, Pojo.class);

    return ResponseEntity.ok(entity.getId());
}

推荐阅读