【问题标题】:How to get ResponseEntity's value in Spring Boot?如何在 Spring Boot 中获取 ResponseEntity 值?
【发布时间】:2019-05-04 18:41:40
【问题描述】:

我是 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');

结果:1​​23456789

【问题讨论】:

    标签: api spring-boot oauth-2.0 httpresponse resttemplate


    【解决方案1】:

    您可以基于 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());
    }
    

    【讨论】:

    • 那么,我怎样才能返回像 x['id'] 这样的分隔 json 值?
    猜你喜欢
    • 2018-11-10
    • 1970-01-01
    • 2021-02-25
    • 2018-03-14
    • 2020-05-24
    • 1970-01-01
    • 2014-10-03
    • 2018-02-20
    • 1970-01-01
    相关资源
    最近更新 更多