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?
(If we don't want to map the complete response structure,) See here: RestTemplate and acessing json
If your
RestTemplateis configured with the default HttpMessageConverters, which is provided by, you may directly get aJackson2ObjectMapperBuilderJsonNodefromrestTemplate.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
RestTemplateis in maintenance mode, with only minor requests for changes and bugs to be accepted going forward. Please, consider using theWebClientwhich offers a more modern API and supports sync, async, and streaming scenarios.
Refs:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With