I am trying fetch some DateTime values stored in a local MySQL database in my Spring App. These dates are parsed into a ZoneDateTime and are then sent to a Client Front End as a json. I have an Object Mapper that specifies this conversion.
@Bean
public ObjectMapper objectMapper() {
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(ZonedDateTime.class,
new ZonedDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")));
return Jackson2ObjectMapperBuilder.json().featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) // ISODate
.modules(javaTimeModule).build();
}
However, on the front-end, the values I receive are in Epoch time instead of the format specified in the ObjectMapper. I have checked the value parsed into ZoneDateTime and it is parsed correctly. My guess is that there is some fault in the process mapping the ZoneDateTime object into the json String value. What could be the fix of this?
Here is how to do it simply and efficiently:
@JsonFormat(shape= JsonFormat.Shape.STRING, pattern="EEE MMM dd HH:mm:ss Z yyyy")
@JsonProperty("created_at")
ZonedDateTime created_at;
This is a quote from a question: [Jackson deserialize date from Twitter to `ZonedDateTime` Also, I don't think that you need to add a special serializer for this. It works for me without this definition just fine.
https://docs.spring.io/spring/docs/4.3.0.RC1_to_4.3.0.RC2/Spring%20Framework%204.3.0.RC2/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.html#timeZone-java.lang.String-
Docs says there is a timezone(String) method to override default timezone.
I suppose you could pass the timezone into this method while building the ObjectMapper
@Bean
public Jackson2ObjectMapperBuilderCustomizer init() {
return new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder builder) {
builder.timeZone(TimeZone.getDefault());
}
};
}
You could use above code to override default timezone.
return Jackson2ObjectMapperBuilder.json().featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) // ISODate
.modules(javaTimeModule).timeZone(TimeZone.getDefault()).build();
You could try this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With