Spring boot Jersey Jackson

后端 未结 1 509
独厮守ぢ
独厮守ぢ 2020-12-04 02:27

I have a question related to the Jackson configuration on my Spring boot project

As described on spring boot blog

I try to customize my Object serialization.

相关标签:
1条回答
  • 2020-12-04 02:32

    The general way to configure the ObjectMapper for JAX-RS/Jersey applications is use a ContextResolver. For example

    @Provider
    public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
    
        private final ObjectMapper mapper;
    
        public ObjectMapperContextResolver() {
            mapper = new ObjectMapper();
            mapper.setPropertyNamingStrategy(
                PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES
            );
        }
    
        @Override
        public ObjectMapper getContext(Class<?> type) {
            return mapper;
        }
    }
    

    It should be picked up with the package scan, or you can explicitly register it, if it's not within the package scope

    public JerseyConfig() {
        register(new ObjectMapperContextResolver());
        // Or if there's is an injection required
        // register it as a .class instead of instance
    }
    

    The ContextResolver is called during the marshalling and unmarshalling. The class/type being serialzed or deserialized into will be passed to the getContext method. So you could even use more than one mapper for different types, or even more use cases.


    UPDATE

    Starting from Spring Boot 1.4, you can just create an ObjectMapper Spring bean, and Spring Boot will create the ContextResolver for you, and use your ObjectMapper

    // in your `@Configuration` file.
    @Bean
    public ObjectMapper mapper() {}
    
    0 讨论(0)
提交回复
热议问题