Configuring a Custom ObjectMapper for Spring RestTemplate
Learn more about creating a custom ObjectMapper for Spring RestTemplate.
Join the DZone community and get the full member experience.
Join For FreeOne of the great things about RestTemplate
is its simplicity. You simply instantiate it like this... RestTemplate restTemplate = new RestTemplate();
and off you go. Under the hood, Spring automatically creates and registers a number of message converters to handle various data formats for requests and responses.
A MappingJackson2HttpMessageConverter
uses Jackson to map POJOs to JSON and vice versa. When the MappingJackson2HttpMessageConverter
is created it's given a new instance of ObjectMapper
. A default instance of ObjectMapper
is fine is many cases, but there are times when you might want to customize the ObjectMapper
used.
You may also like: How to Use Spring RESTTemplate to Post Data to a Web Service
For example, I ran into an issue recently where I needed to configure Jackson to accept case insensitive properties like this.
private ObjectMapper createObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
return objectMapper;
}
To make the custom ObjectMapper
available to MappingJackson2HttpMessageConverter
, simply create a new MappingJackson2HttpMessageConverter
and pass in the ObjectMapper
instance.
private MappingJackson2HttpMessageConverter createMappingJacksonHttpMessageConverter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(createObjectMapper());
return converter;
}
Then, you can create a RestTemplate
and add your custom MappingJackson2HttpMessageConverter
to its list of message converters.
@Bean
public RestTemplate createRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(0, createMappingJacksonHttpMessageConverter());
}
Note that you should add it to the beginning of the list so that it takes precedence over the default MappingJackson2HttpMessageConverter
that Spring has already registered.
Further Reading
How to Use Spring RESTTemplate to Post Data to a Web Service
Published at DZone with permission of Brian Hannaway, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments