How do I obtain the Jackson ObjectMapper in use by Spring 4.1?
If you're using Spring Boot with Jackson on your classpath and default implementation for JSON parsing in your REST controller, then this should work:
@Autowiredprivate ObjectMapper jacksonObjectMapper;
As was said by others, you can't @Autowired
it in directly into your controller.
@Emerson Farrugia's suggestion to create a new instance using
Jackson2ObjectMapperBuilder.json().build()
also didn't work for me because the obtained instance was not following the spring.jackson.*
configuration properties, which I needed it to.
The solution I found was to obtain the ObjectMapper from Spring's MappingJackson2HttpMessageConverter
which is injectable.
So I autowired it:
@Autowiredprivate MappingJackson2HttpMessageConverter springMvcJacksonConverter;
and then get the ObjectMapper from it like this:
ObjectMapper objectMapper = springMvcJacksonConverter.getObjectMapper();
This instance behaves exactly as Spring MVC's own message conversion - it probably is the same instance anyway.
If you take a look at MappingJackson2HttpMessageConverter
, you'll see that it creates a new ObjectMapper
, but doesn't expose it as a bean. There's a getter, but the only way I've fished it out in the past is when I created the MappingJackson2HttpMessageConverter
myself, e.g.
public class WebMvcConfiguration extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { MappingJackson2HttpMessageConverter jacksonMessageConverter = new MappingJackson2HttpMessageConverter(); ObjectMapper objectMapper = jacksonMessageConverter.getObjectMapper(); objectMapper.registerModule(new JodaModule()); objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true); converters.add(jacksonMessageConverter); }}
If you're working with Spring Boot, there's a section in the manual dedicated to working with the ObjectMapper
If you create a default Jackson2ObjectMapperBuilder
@Bean
, you should be able to autowire that same ObjectMapper
instance in your controller.