Register Jackson MixIn in JavaEE application

心已入冬 提交于 2019-12-11 09:32:00

问题


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.


回答1:


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 defaultMapper;
    }  
}

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



来源:https://stackoverflow.com/questions/29767579/register-jackson-mixin-in-javaee-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!