Issue
I do restTemplate call and receive rawMap. From debug I see that key class and value class are String. Its ok because service that response to my restTemplate sends map in JSON. Now I want to crate Map with this code:
Map<String, Integer> gameIdsMap = new HashMap<>();
rawGameIdsMap.forEach(((key, value) -> gameIdsMap.put(String.valueOf(key), Integer.parseInt(String.valueOf(value)))));
Im curious. Is there more efficient and more clear way to do it?
I cant just receive from restTemplate Map <String,Integer>
.
RestTemplate
Map rawGameIdsMap = Objects.requireNonNull(restTemplate.getForObject(uriFactory.getReverseGameIdsURI(), Map.class));
Solution
The RestTemplate
class provides several exchange()
methods.
It allows to specify as parameter an instance of ParameterizedTypeReference
which the aim is to capture and pass a generic type.
So you could do something like :
Map<String, String> gameIdsMap = Objects.requireNonNull(
template.exchange(uri, HttpMethod.GET, null, new ParameterizedTypeReference<Map<String, String>>() {
}).getBody());
Doing it :
Map<String, Integer> gameIdsMap= Objects.requireNonNull(
template.exchange(uri, HttpMethod.GET, null, new ParameterizedTypeReference<Map<String, Integer>>() {
}).getBody());
is aslo correct (at least with Jackson) but if the value cannot be converted to an Integer
. In this case, it will provoke a deserialiaztion exception at runtime.
Answered By - davidxxx
Answer Checked By - Clifford M. (JavaFixing Volunteer)