pdeva
pdeva

Reputation: 45451

Spring RestTemplate unable to parse json response

If I parse the response of a POST as string it works perfectly:

ResponseEntity<String> stringResponse = restTemplate.postForEntity(DruidClient.QUERY_HOST + "/druid/v2", query, String.class);
String valueResults = stringResponse.getBody();
DruidValueResult[] results = new ObjectMapper().readValue(valueResults, DruidValueResult[].class);

However, if i tell spring to parse the response directly:

ResponseEntity<DruidValueResult[]> results = restTemplate.postForEntity(DruidClient.QUERY_HOST + "/druid/v2", query, DruidValueResult[].class);

I get the following error:

org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class [Lcom.dripstat.metricprocessor.druid.DruidValueResult;] and content type [application/smile]
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:108)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:788)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:773)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:553)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:506)
at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:361)

Why isn't spring able to parse the resulting json directly?

Upvotes: 1

Views: 4221

Answers (1)

tmarwen
tmarwen

Reputation: 16354

From SpringSource Blog:

Objects passed to and returned from the methods getForObject(), postForLocation(), and put() and are converted to HTTP requests and from HTTP responses by HttpMessageConverters. Converters for the main mime types and Java types are registered by default, but you can also write your own converter and plug it in the RestTemplate. In the example below, I will show you how that's done.

I suppose the same for postForEntity(), so you may need to add a message converter for your specific mime type since it is not marshelled by default:

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
  <property name="messageConverters">
    <list>
      <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes" value="application/smile" />
        <property name="supportedMediaTypes" value="text/javascript" />
      </bean>
    </list>
  </property>
</bean>

Upvotes: 2

Related Questions