2018 年 2 月 5 日更新(大约 4 年后)…我再次测试了这个,因为人们一直在支持我的问题/答案,Sotirios Delimanolis 是正确的,我不必在我的答案中编写代码来完成这项工作。我使用了与我的问题中所示基本相同的 RestTemplate/REST 服务设置,REST 服务具有已确认的响应内容类型 application/json,并且 RestTemplate 能够毫无问题地将响应处理到 Map 中。
我正在调用一个返回 JSON
的休息服务,如下所示:
{
"some.key" : "some value",
"another.key" : "another value"
}
我想我可以使用 java.util.Map
作为响应类型来调用此服务,但这对我不起作用。我得到这个例外:
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [interface java.util.Map]
我是否应该只指定 String
作为响应类型并将 JSON
转换为 Map
?
编辑我
这是我的 restTemplate 调用:
private Map<String, String> getBuildInfo(String buildUrl) {
return restTemplate.getForObject(buildUrl, Map.class);
}
这是我设置 restTemplate 的方式:
@PostConstruct
public void initialize() {
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new ClientHttpRequestInterceptor() {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
HttpRequestWrapper requestWrapper = new HttpRequestWrapper(request);
requestWrapper.getHeaders().setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
return execution.execute(requestWrapper, body);
}
});
restTemplate.setInterceptors(interceptors);
}
编辑二
完整的错误信息:
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]
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:108) ~[spring-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:549) ~[spring-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:502) ~[spring-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:239) ~[spring-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
at idexx.ordering.services.AwsServersServiceImpl.getBuildInfo(AwsServersServiceImpl.java:96) ~[classes/:na]
原文由 Zack Macomber 发布,翻译遵循 CC BY-SA 4.0 许可协议
正如我之前指出的,您的错误消息向我们表明您正在接收
application/octet-stream
作为Content-Type
。因此,杰克逊的
MappingJackson2HttpMessageConverter
无法解析内容(它期望application/json
)。原答案:
假设您的 HTTP 响应的
Content-Type
是application/json
并且您在类路径上有 Jackson 1 或 2,一个RestTemplate
java.util.Map
就好了。你得到的错误,你没有完整显示,要么你注册了自定义
HttpMessageConverter
覆盖默认对象的对象,要么你的类路径上没有 Jackson 和MappingJackson2HttpMessageConverter
未注册(这将进行反序列化)或者您没有收到application/json
。