更新
无需创建自定义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());