How can I change Jacksons Configuration when using Spring Data REST?

前端 未结 4 957
予麋鹿
予麋鹿 2021-01-16 09:37

I\'m trying to configure Jackson to show JSR 310 instants in ISO 8601 format.

@Configuration
class Jackson {

    @Bean
    static ObjectMapper objectMapper(         


        
相关标签:
4条回答
  • 2021-01-16 10:18

    You can (and probably should) you RepositoryRestConfigurerAdapter (in Spring Data Rest 2.4) or RepositoryRestMvcConfiguration which expose the configureObjectMapper method.

    @Configuration
    class RepositoryRestAdapterConfiguration extends RepositoryRestConfigurerAdapter {
    
        @Override
        public void configureJacksonObjectMapper(ObjectMapper objectMapper) {
            objectMapper.registerModule(new JavaTimeModule());
            objectMapper.disable( SerializationFeature.WRITE_DATES_AS_TIMESTAMPS );
        }
    
    }
    
    0 讨论(0)
  • 2021-01-16 10:18

    Actually, you could make it more bootify just using jackson auto-configuration properties in application.properties (or application.yml):

    spring.jackson.serialization.write_dates_as_timestamps=false
    
    0 讨论(0)
  • 2021-01-16 10:19

    After some experimentation, I found that if I annotate my "setter" (setter injection) with it will get run. This is a little simpler, and cleaner than using field injection and @PostConstruct.

    @Configuration
    class Jackson {
    
       @Autowired
       void configureObjectMapper( final ObjectMapper objectMapper ) {
        objectMapper.disable( SerializationFeature.WRITE_DATES_AS_TIMESTAMPS );
       }
    }
    
    0 讨论(0)
  • 2021-01-16 10:22

    I think one way could be to inject the ObjectMapper in a suitable bean class and then do the setting in a @PostConstruct method, e.g.:

    @Configuration // or @Service or some bean
    public class SomeClass ... {
    
        @Autowired
        private ObjectMapper objectMapper;
    
        @PostConstruct
        private void configureObjectMapper() {
            objectMapper.disable( SerializationFeature.WRITE_DATES_AS_TIMESTAMPS );
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题