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:

@Autowired
private 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:

@Autowired
private 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.