web是用Content-Type:text/plain; charset=utf-8来响应请求的,但是消息的格式就像JSON一样,例如。
{
"total": 168,
"page": 0,
"pageCount": 1,
...
}在Spring中,使用RestTemplate处理此消息,并自动将JSON映射到ModelDto POJO,
restTemplate.getForObject(url, ModelDto::class.java) 这会产生以下错误:
org.springframework.web.client.RestClientException:无法提取响应:没有为响应类型类api.ModelDto和内容类型文本/平原找到合适的HttpMessageConverter;charset=utf-8
是否有任何方法让spring将此消息当作JSON对待,并将其解析为JSON,尽管内容类型是明文的?
发布于 2018-03-25 14:31:37
更新
不需要创建自定义HttpMessageConverter,因为AbstractHttpMessageConverter有一个方法setSupportedMediaTypes,可用于更改受支持的媒体类型:
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Arrays.asList(MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON));
restTemplate.getMessageConverters().add(0, converter);我认为通过实现自己的HttpMessageConverter<T>是可能的。
RestTemplate使用它将原始响应转换为某种表示(例如POJO)。因为它有一个转换器列表,所以它会根据其类型(例如application/json等)为特定响应找到特定的转换器。
因此,HttpMessageConverter<T>的实现应该类似于默认的MappingJackson2HttpMessageConverter,但是支持更改的媒体类型:
public class MappingJackson2HttpMessageConverter2 extends AbstractJackson2HttpMessageConverter {
private String jsonPrefix;
public MappingJackson2HttpMessageConverter2() {
this(Jackson2ObjectMapperBuilder.json().build());
}
public MappingJackson2HttpMessageConverter2(ObjectMapper objectMapper) {
// here changed media type
super(objectMapper, MediaType.TEXT_PLAIN);
}
public void setJsonPrefix(String jsonPrefix) {
this.jsonPrefix = jsonPrefix;
}
public void setPrefixJson(boolean prefixJson) {
this.jsonPrefix = (prefixJson ? ")]}', " : null);
}
@Override
protected void writePrefix(JsonGenerator generator, Object object) throws IOException {
if (this.jsonPrefix != null) {
generator.writeRaw(this.jsonPrefix);
}
String jsonpFunction =
(object instanceof MappingJacksonValue ? ((MappingJacksonValue) object).getJsonpFunction() : null);
if (jsonpFunction != null) {
generator.writeRaw("/**/");
generator.writeRaw(jsonpFunction + "(");
}
}
@Override
protected void writeSuffix(JsonGenerator generator, Object object) throws IOException {
String jsonpFunction =
(object instanceof MappingJacksonValue ? ((MappingJacksonValue) object).getJsonpFunction() : null);
if (jsonpFunction != null) {
generator.writeRaw(");");
}
}
}然后可以将其添加到RestTemplate对象中:
restTemplate.getMessageConverters().add(0, new MappingJackson2HttpMessageConverter2());https://stackoverflow.com/questions/49469954
复制相似问题