error code
public static void main(String[] args)throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
final LocalDateTime localDateTime = LocalDateTime.now();
final String s = objectMapper.writeValueAsString(localDateTime);
System.out.println(s);
}
Error
reason
The date was not formatted during conversion
Solution:
public static void main(String[] args)throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
// Date and time formatting
JavaTimeModule javaTimeModule = new JavaTimeModule();
// Set the serialization format of LocalDateTime
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
objectMapper.registerModule(javaTimeModule);
final LocalDateTime localDateTime = LocalDateTime.now();
final String s = objectMapper.writeValueAsString(localDateTime);
System.out.println(s);
}