1. 程式人生 > >Spring Boot 中 Java8 LocalDateTime 序列化問題

Spring Boot 中 Java8 LocalDateTime 序列化問題

LoginController頁面如下:

public Object login(@RequestBody User user) { 
   return xxxx;  
}

User 類屬性:
private LocalDateTime birthDay;  //出生日期

postman測試:

傳入日期 "birthDay": "2014-01-01T01:00:00", 後臺可以接收

傳入"birthDay": "2014-01-01 01:00:00", 頁面有如下異常資訊:

"message": "JSON parse error: Can not deserialize value of type java.time.LocalDateTime from String \"2018-11-09 12:36:28.242\": Text '2018-11-09 12:36:28.242' could not be parsed at index 10; 
nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type java.time.LocalDateTime from String \"2018-11-09 12:36:28.242\":
 Text '2018-11-09 12:36:28.242' could not be parsed at index 10\n at [Source: 
[email protected]
;

自己確實花了點時間。終於解決:

本文中用的序列化方式為:

Maven: com.fasterxml.jackson.core:jackson-databind:2.8.8

    @Bean
    public ObjectMapper objectMapper() {
        bjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new Jdk8Module());
        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.registerModule(new GuavaModule());
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    }

1.為什麼傳2014-01-01T01:00:00 這個字串可以被後臺解析呢?

原因在JavaTimeModule類中:

預設配置對LocalDateTime配置序列化和反序列化類

LocalDateTimeSerializer類預設日期格式,有個 T 拼接字元,問題就出在這裡,所以2014-01-01 01:00:00後臺反序列化失敗

解決程式碼:自己指定日期解析格式

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new Jdk8Module());
JavaTimeModule module = new JavaTimeModule();
module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
objectMapper.registerModule(module);

部落格寫的不是很好,爭取慢慢有改變。