3

I have this call I am making with

ResponseEntity<String> response = new RestTemplate().exchange(url, HttpMethod.GET, request, String.class);
        String json = response.getBody();

This returns the following json

{
  "id": "T-5IB4VHCDNJs9AAQr31zQlKRjfA0WEnMe1pLrp5irXRRnw",
  "accountId": "qi0oxfBt0C968y6ku1rsxWeqSDolBFWYRlLgxVTo5FHVIeQ",
  "puuid": "HDzjdaStxhHcceGGd8qJcc4Vw45FOlOQ1PNXKQ0h9_iqfwHP3oI0spl1bLUOw_7_J49vzaIKylv5Vg",
  "name": "King yibz",
  "profileIconId": 4072,
  "revisionDate": 1639613941000,
  "summonerLevel": 221
}

what is the best way to just return the summonerLevel value?

htmlhelp32
  • 141
  • 1
  • 12

1 Answers1

2

(If we don't want to map the complete response structure,) See here: RestTemplate and acessing json

If your RestTemplate is configured with the default HttpMessageConverters, which is provided by Jackson2ObjectMapperBuilder, you may directly get a JsonNode from restTemplate.getForObject (/getForEntity/exchange/put/post/patch/...).

Nowadays it would be the MappingJackson2HttpMessageConverter [ref], but we still can obtain a (com.fasterxml.jackson.databind.)JsonNode like:

ResponseEntity<JsonNode> response = new RestTemplate().exchange(
  url, 
  HttpMethod.GET, 
  request, // ??
  JsonNode.class
); // in a GET request parameters are normally in URL!, so we could:
// ResponseEntity<JsonNode> resultEnt = restTemplate.getForEntity(url+queryString, JsonNode.class);
// Or if we don't need the ResponseEntity at all (status, header, ...), just:
// JsonNode resultObj = restTemplate.getForObject(url + query, JsonNode.class);
JsonNode json = response.getBody();

We can then extract "summonerLevel" like:

int summonerLevel = json.findValue("summonerLevel").asInt(); // (more) exceptions possible!

Please also keep in mind:

As of (spring(-web)) 5.0 the RestTemplate is in maintenance mode, with only minor requests for changes and bugs to be accepted going forward. Please, consider using the WebClient which offers a more modern API and supports sync, async, and streaming scenarios.

Refs:

xerx593
  • 12,237
  • 5
  • 33
  • 64