0

In my code, I am using RestTemplate to call an external API and receive a complex JSON response. However, for my specific use case, I only need to return the JSON as-is to the front-end. To achieve this, I have chosen to map the response to a Map<String, Object>.

Currently, I have observed that the mapping works well, and during debugging, I can see that it returns a LinkedHashMap, which suits my requirements as I need the values to be ordered. However, I would like to confirm if this behavior is consistent and reliable.

My question is: How can I determine if the mapping operation will always return a LinkedHashMap or if it could potentially return a different implementation, such as a HashMap?

I have searched for relevant documentation but haven't been able to find any specific information regarding the implementation returned by RestTemplate when mapping JSON responses to a Map.

Any insights or pointers to relevant documentation would be greatly appreciated. Thank you!

Here's my code:

ParameterizedTypeReference<Map<String, Object>> responseType = new ParameterizedTypeReference<Map<String, Object>>() {};
return restTemplate.exchange(uri, HttpMethod.POST, new HttpEntity<>(request, getHeaders()), responseType).getBody();

Edit: i tried to convert the response to a String but i got the error:

Error while extracting response for type [class java.lang.String] and content type [application/json]

Here's my new code:

return restTemplate.postForObject(uri, new HttpEntity<>(request, getHeaders()), String.class);
  • Why not just a `String` and pass that on? Instead of String -> Map -> String? What the returned object is is solely to the implementation in this case Jackson, so will it always be a `LinkedHashMap` could be or couldn't be. But as mentioned why map it to a `Map` of you are going to turn it into the same JSON anyway, just pass it along. – M. Deinum Jul 13 '23 at 09:05
  • Are you performing any operations on that Map? – Shekhar Jul 13 '23 at 09:13
  • yes, sometimes i do perform some operation on the response so i need to map it – Calu River Jul 13 '23 at 09:51
  • @M.Deinum actually i tried to convert the response to a String but i get: Error while extracting response for type [class java.lang.String] and content type [application/json] .... here's my code: return restTemplate.postForObject(uri, new HttpEntity<>(request, getHeaders()), String.class); – Calu River Jul 17 '23 at 09:12
  • Please don't provide additional code as comments as that is totally unreadable. Please edit your question and add the full error stacktrace you get. – M. Deinum Jul 17 '23 at 09:24
  • @M.Deinum oh i'm sorry, im new to this, actually i have edited my post. Your feedback would be really appreciated! – Calu River Jul 17 '23 at 09:31
  • Do you get a larger stacktrace or just this snippet? I would expect a bit more actually. – M. Deinum Jul 17 '23 at 09:33

0 Answers0