How to extract ObjectMapper from JAX-RS Client?

前端 未结 3 1489
逝去的感伤
逝去的感伤 2020-12-17 19:01

I am using Jersey JAX-RS client (version 2.0). I know it is using a Jackson ObjectMapper to generate and parse JSON. I want to use that same object to generate JSON for some

3条回答
  •  不知归路
    2020-12-17 19:14

    Jersey does not actually explicitly configure an ObjectMapper instance, rather it delegates to JacksonJsonProvider, which in turn uses a default mapper instance. You can trace through the JacksonProviderProxy code to see how it works. You can create and customize a shared mapper to be used throughout your application by defining a context resolver:

    @Provider
    public class ObjectMapperContextResolver implements
            ContextResolver {
        private ObjectMapper mapper = null;
    
        public ObjectMapperContextResolver() {
            super();
    
            // Illustrate configuration of the mapper instance
            mapper = new ObjectMapper().configure(
                    SerializationConfig.Feature.WRAP_ROOT_VALUE, true).configure(
                    DeserializationConfig.Feature.UNWRAP_ROOT_VALUE, true);
        }
    
        @Override
        public ObjectMapper getContext(Class type) {
            return mapper;
        }
    }
    

    The Jackson provider will retrieve its mapper instance from this resolver, and you could do the same in your code, as so:

    public class MyResource {
        @Context
        private ContextResolver mapperResolver;
    
        public void someResourceMethod() {
            final ObjectMapper mapper = mapperResolver.getContext(Object.class);
        }
    }
    

提交回复
热议问题