resttemplate getForObject map responsetype
RestTemplate has a method named exchange that takes an instance of ParameterizedTypeReference as parameter.
To make a GET request that returns a java.util.Map
, just create an instance of an anonym class that inherits from ParameterizedTypeReference.
ParameterizedTypeReference<HashMap<String, String>> responseType =
new ParameterizedTypeReference<HashMap<String, String>>() {};
You can then invoke the exchange method:
RequestEntity<Void> request = RequestEntity.get("http://example.com/foo")
.accept(MediaType.APPLICATION_JSON).build();
Map<String, String> jsonDictionary = restTemplate.exchange(request, responseType).getBody();
I think you can achieve what you're aiming for simply using the RestTemplate and specifying a JsonNode as the response type.
ResponseEntity<JsonNode> response =
restTemplate.exchange(url, HttpMethod.GET, entity, JsonNode.class);
JsonNode map = response.getBody();
String someValue = map.get("someValue").asText();
As I had previously noted, your error message is showing us that you are receiving application/octet-stream
as a Content-Type
.
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [interface java.util.Map] and content type [application/octet-stream]
As such, Jackson's MappingJackson2HttpMessageConverter
cannot parse the content (it's expecting application/json
).
Original answer:
Assuming your HTTP response's Content-Type
is application/json
and you have have Jackson 1 or 2 on the classpath, a RestTemplate
can deserialize JSON like you have into a java.util.Map
just fine.
With the error you are getting, which you haven't shown in full, either you've registered custom HttpMessageConverter
objects which overwrite the defaults ones, or you don't have Jackson on your classpath and the MappingJackson2HttpMessageConverter
isn't registered (which would do the deserialization) or you aren't receiving application/json
.