I'm newbie in Spring Boot. I got response from API with responseEntity in Spring Boot. I returned value of response. But I want define an array/json and set response value to this array/json. After that, I want to get specific value of this array. For example;
returned value:
{"id":"123456789","license":"6688","code":"D8B1H832EE45"}
I want to take only id's value 123456789.
something like;
array['id']
How can I do it? Help me please.
@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);
}
it's wrong i know but i just want something like: x.getBody('id');
result: 123456789
You could model a Pojo (Plain old java object) based on the json like the following:
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;}
}
Then change your endpoint to the following signature:
@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());
}