0

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));
Anton Kolosok
  • 482
  • 9
  • 24

1 Answers1

2

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.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • @Sotirios Delimanolis Do you have a Jackson/Gson reference or a concrete example that shows that such a thing? Sorry, not time to write a real test now. – davidxxx Aug 19 '19 at 14:40
  • I have a doubt for the last one with `exchange()` of Spring template. I will give it a go. – davidxxx Aug 19 '19 at 14:47
  • 1
    @Sotirios Delimanolis I checked that. It works as you said. At least with Jackson. I would delete my answer but cannot since it is accepted. I updated for at least to be conform to the reality. – davidxxx Aug 19 '19 at 15:09