Initially, the default ObjectMapper used by the Jackson provider is not used. It does not use ObjectMapper at all. It uses other Jackson APIs to handle serialization (de).
If you want to use / insert one instance of ObjectMapper , then you just need to create a Factory for it
public class ObjectMapperFactory implements Factory<ObjectMapper> { final ObjectMapper mapper = new ObjectMapper(); @Override public ObjectMapper provide() { return mapper; } @Override public void dispose(ObjectMapper t) {} }
Then tie it
register(new AbstractBinder(){ @Override public void configure() { bindFactory(ObjectMapperFactory.class) .to(ObjectMapper.class).in(Singleton.class); } });
It should be noted that any configuration of ObjectMapper not thread protected . Therefore, say that you tried to configure it from your resource method, these operations are not thread safe.
Another thing that should be noted with the Jackson provider is that if we provide a ContextResolver , such as the @Laurentiu L mentioned , the Jackson provider will switch to using our ObjectMapper . In this case, if you want to use the same ObjectMapper , you can find it in Factory . for example
public class ObjectMapperFactory implements Factory<ObjectMapper> { private final Providers providers; final ObjectMapper mapper = new ObjectMapper(); public ObjectMapperFactory(@Context Providers providers) { this.providers = providers; } @Override public ObjectMapper provide() { ContextResolver<ObjectMapper> resolver = providers.getContextResolver( ObjectMapper.class, MediaType.APPLICATION_JSON); if (resolver == null) { return mapper; } return resolver.getContext(null); } @Override public void dispose(ObjectMapper t) {} }
In order for the above to work (use one ObjectMapper ), you need to make sure that you are using ContextResolver<ObjectMapper> , and make sure that the ContextResolver annotation matches the corresponding @Produces and @Consumes .
Paul samsotha
source share