Java – ZonedDateTime is returned in Spring App as a Epoch Times time instead of a standard string

ZonedDateTime is returned in Spring App as a Epoch Times time instead of a standard string… here is a solution to the problem.

ZonedDateTime is returned in Spring App as a Epoch Times time instead of a standard string

I’m trying to get some DateTime values stored in a local MySQL database in my Spring application. These dates are parsed as ZoneDateTime and then sent to the client frontend as json. I have an object mapper that specifies this transformation.

@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 frontend, the value I receive is the Epoch Times time, not the format specified in ObjectMapper. I’ve checked the value that resolves to ZoneDateTime and it is parsed correctly. My guess is that there was some error in mapping the ZoneDateTime object to the json String value.
Is there any way to fix this?

Solution

Here’s 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;

Here is a quote to a question: [ Jackson deserialize date from Twitter to `ZonedDateTime`
Also, I don’t think you need to add a special serializer for this. Without this definition, it’s fine for me.

Related Problems and Solutions