Spring 4.1 instantiates a Jackson ObjectMapper
instance. I have reason to want to @Autowire
that instance into one of my controllers: The controller does some minor JSON parsing of its own using Jackson, but the ObjectMapper
it uses should be the one and same instance that Spring itself is using. How do I go about accomplishing that?
Note that I'm not asking how to custom configure the ObjectMapper
in use by Spring; I'm happy with the defaults. I just want to fish the instance used by Spring out so that I can re-use the existing instance in my own code.
Overview. When using JSON format, Spring Boot will use an ObjectMapper instance to serialize responses and deserialize requests. In this tutorial, we'll take a look at the most common ways to configure the serialization and deserialization options. To learn more about Jackson, be sure to check out our Jackson tutorial.
If you use Spring Boot, the jackson-databind dependency comes in the spring-boot-starter-json module (which also is included in other spring boot started moduled, like spring-boot-starter-web ).
ObjectMapper is the main actor class of Jackson library. ObjectMapper class ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions.
Note that copy() operation is as expensive as constructing a new ObjectMapper instance: if possible, you should still pool and reuse mappers if you intend to use them for multiple operations.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With