Search code examples
javajsonresttemplate

JSON Map collection to ArrayList


Need help with the following case - with RestTemplate I get a response from internal server via:

Map<String, String> response = RestTemplate.getForObject(url, Map.class);

structure of the response is:

"mainRate" -> 2.99000  // double
"secondaryRates" -> [{rateName -> r1, rateVal -> 5.9}] //ArrayList of LinkedHashMap<String, Double>

First question - I cannot read from map result in a plain way as:

double mainRate = response.get("mainRate")

This would give ClassCastException. Have no idea why? Anybody had such case? Instead, I do:

double mainRate = Double.parseDouble(String.valueOf(response.get("mainRate")));

Kindly advise why simple way of response.get(keyName) doesn't work? It works only with conversions to String and then to double.

Second issue is with collection - how to parse nested collection of the object?


Solution

  • So, after some investigation I tried using @JSONProperty annotation on the fields of my end object and it all worked.

    This is, however, not clear to my why it wasn't possible retrieving values without it