I have a jersey2 application configured for JSON support via Jackson, adding
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
</dependency>
in the POM file and
public MyApplication() {
...
register(JacksonFeature.class)
...
}
in my application. Everything works, my resources get deserialized POJOs as arguments
@POST @Consumes(MediaType.APPLICATION_JSON)
public void blah(MyPojo p) {
...
}
Now one of thoese resources needs a reference to Jackson's ObjectMapper
to do some deserialization on its own. I've tried doing something like
@Inject
public MyResource(@Context ObjectMapper mapper) {
...
}
or
@GET
public String foo(@Context ObjectMapper mapper) {
...
}
but in both cases the reference to mapper
is null. How can I inject a reference to the ObjectMapper
in my resources?
First there is no default
ObjectMapper
used by the Jackson provider. It doesn't use anObjectMapper
at all actually. It makes use of other Jackson APIs to handle the (de)serialization.If you want to use/inject a single
ObjectMapper
instance, then you should just create aFactory
for itThen bind it
One thing should be noted is that any configuration of the
ObjectMapper
is not thread safe. So say you tried to configure it from your resource method, those operations are not thread safe.Another thing to note with the Jackson provider, is that if we provide a
ContextResolver
, like mentioned by @Laurentiu L, then the Jackson provider will switch to using ourObjectMapper
. In which case, if you want to use that sameObjectMapper
, then you can look it up in theFactory
. For exampleFor the above to work (use a single
ObjectMapper
), you need to make sure to implement theContextResolver<ObjectMapper>
, and make sure to annotation theContextResolver
with the corresponding@Produces
and@Consumes
media types.Aside from the JacksonFeature you need to register a ContextResolver for ObjectMapper.
Simple example from the Documentation at 9.1.4.2. Configure and register
Complete code example available on Github
You will also need to register it