thomas.mc.work
thomas.mc.work

Reputation: 6474

Register Jackson MixIn in JavaEE application

On the basis of this setup (using Jackson as JAXB-provider in a JavaEE application): How can I register my MixIn modules?

In my client application using the JAX-RS client feature it is registered automatically. I've seen this SO post, but where do I get the ObjectMapper from? I've tried to create on in my ServletContextListener and register the module there. But of course the mapper instance will be disposed after the contextInitialized method ends.

Upvotes: 2

Views: 951

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 209082

Use a ContextResolver as seen in this post. With the @Provider annotation, the ContextResolver should be picked up from the scanning (assuming you are using kind of scanning; package scanning or classpath scanning)

@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {

    final ObjectMapper mapper = new ObjectMapper();

    public ObjectMapperContextResolver() {
        mapper.registerModule(new MixinModule());
    }

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return mapper;
    }  
}

What happens, is that the MessageBodyReader/MessageBodyWrite provided by your Jackson JAX-RS provider, will call the getContext method, to get the ObjectMapper

Upvotes: 2

Related Questions