Jackson2JsonMessageConverter以特定模式序列化LocalDateTime

时间:2018-07-12 13:43:37

标签: json date spring-boot

我正在尝试使用RabbitMQ和SpringBoot发送事件。

@Configuration类:

  @Bean
   public Jackson2JsonMessageConverter producerJackson2MessageConverter() {
            return new Jackson2JsonMessageConverter();
    }

事件类:

public class TheEvent{

    @JsonFormat(pattern = "dd::MM::yyyy")
    private  LocalDateTime date;
//setters getters

}

当我发送它时,它的到达时间是:

{"month":"JULY","year":2018,"dayOfMonth":12,"dayOfWeek":"THURSDAY","dayOfYear":193,"hour":16,"minute":29,"nano":835000000,"second":24,"monthValue":7,"chronology":{"id":"ISO","calendarType":"iso8601"}},"direction":1}"

如何以预定义模式序列化此日期对象? (请记住,我只是在注册bean Jackson2JsonMessageConverter)

也尝试过:

@Bean
    @Primary
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {      
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
        return objectMapper;
    }

1 个答案:

答案 0 :(得分:1)

它对我有用:

@Bean
public Jackson2JsonMessageConverter converter(Jackson2ObjectMapperBuilder builder) {
    ObjectMapper objectMapper = builder.createXmlMapper(false).build();
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
    return new Jackson2JsonMessageConverter(objectMapper);
}

在项目中,我使用RabbitListener和那个Jackson2JsonMessageConverter

侦听器:

@RabbitListener(queues = "${spring.rabbitmq.queue}")
@Transactional
public void receiveSocialPost(SocialPost socialPost) {
}