Configuring a Custom ObjectMapper for Spring RestTemplate
One 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 case but there are times when you might want to customise the ObjectMapper
used. 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.
Leave A Comment