api - 如何在 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
解决方案
您可以基于 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());
}
推荐阅读
- sybase - 将二维码添加到 powerbuilder 10.5 数据窗口
- groovy - 获取具有运行 TestCase 步骤的 TestCase 名称的 Groovy 脚本
- c++ - 类内部和外部的静态 constexpr 元组之间的区别
- prestashop - 在 presta 1.7 中清空 ps_stock
- java - Mockito.verify 与 KafkaProducer 和 ProducerRecord
- c# - 按字符串属性对对象进行排序,最后是空字符串
- javascript - 添加类后如何保持 HTML 元素抖动/移动
- symfony - 按innerJoin 表与学说排序
- java - Java LocalDateTime/ OffsetDateTime 到 Swift 4
- visual-studio-code - VSCode 扩展激活事件 onCreate file