UPDATED
There's no need to create a custom HttpMessageConverter
since AbstractHttpMessageConverter
has a method setSupportedMediaTypes
which can be used to change supported media type:
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Arrays.asList(MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON));
restTemplate.getMessageConverters().add(0, converter);
I think it's possible via implementing own HttpMessageConverter<T>
.
RestTemplate
uses it to convert a raw response to some representation (for instance, POJO). Since it has a list of converters, it finds specific converter for a particular response by its type (e.g application/json
, etc).
So your implementation of HttpMessageConverter<T>
should be something like default MappingJackson2HttpMessageConverter
but with changed supported media type:
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(");");
}
}
}
Then you can add this to RestTemplate
object:
restTemplate.getMessageConverters().add(0, new MappingJackson2HttpMessageConverter2());