Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't serialize java.time.LocalDate as a String with Jackson

I am using spring-boot 1.2.1.RELEASE with jackson 2.6.2 including the jsr310 datatype. I am using the annotation @SpringBootApplication to kick off my Spring app. I have

spring.jackson.serialization.write_dates_as_timestamps = false

set in my application.properties (which I know is being read because I tested with banner = false).

And yet java.time.LocalDate is still being serialized as an array of integers. I am not using @EnableWebMvc.

It looks like if I add the tag

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")

to my LocalDate variable then it works. But I thought it was automatic with the above property set. Plus, if I remember right (I've since just decided to work with the integer array), that only worked with serialization and not deserialization (but I can't honestly quite remember if that last part is true).

like image 263
crowmagnumb Avatar asked Oct 05 '15 15:10

crowmagnumb


2 Answers

This is know issue in Spring Boot. You need to do it manually.

objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

or update to 1.2.2.

UPDATE: Also there is a way to configure ObjectMapper used by spring from your container.

like image 180
Denis Bazhenov Avatar answered Nov 17 '22 04:11

Denis Bazhenov


I had the same problem of LocalDateTime being serialized as an array of integers like [2019,10,14,15,7,6,31000000]. The spring boot version I had was 1.5.13.RELEASE. I had to register the JavaTimeModule on the ObjectMapper being used to solve this. Below is my ObjectMapper config that worked for me:

@Bean
  public ObjectMapper getObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.registerModule(new JavaTimeModule());
    return mapper;
  }
like image 1
Madhu Bhat Avatar answered Nov 17 '22 03:11

Madhu Bhat