5

I am trying to understand why does Jackson transform ZonedDateTime to Decimal while getting MvcResult in a spring intergration Test ?

Here is the expected date : 2019-10-01T10:10:44+02:00[Europe/Paris] and the actual result : 1572426644.000000000

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
the_tourist
  • 191
  • 2
  • 13
  • 2
    Because `ZoneDateTime` is an timestamp. – Zorglube Oct 10 '19 at 12:20
  • 1
    Which conversion had you expected or wanted instead? – Ole V.V. Oct 10 '19 at 12:35
  • 1
    Try to register `JavaTimeModule` module. Take a look at: [Spring Boot Jackson date and timestamp Format](https://stackoverflow.com/questions/55256567/spring-boot-jackson-date-and-timestamp-format/55270120#55270120), [Umarshalling MonthDay spring jackson json](https://stackoverflow.com/questions/55180301/umarshalling-monthday-spring-jackson-json), [Problem with deserialization of LocalDateTime in Junit test](https://stackoverflow.com/questions/55107588/problem-with-deserialization-of-localdatetime-in-junit-test) – Michał Ziober Oct 10 '19 at 20:33

3 Answers3

2

Here is the answer that gives a precise solution to your question: Spring Data JPA - ZonedDateTime format for JSON serialization. In short, you need to annotate your ZonedDateTime as follows.

ZonedDateTime time = ZonedDateTime.now();

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
public ZonedDateTime getTime() {
    return time;
}

You also might need to add the dependency for JSR-310

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.6.0</version>
</dependency>
Michael Gantman
  • 7,315
  • 2
  • 19
  • 36
2

If you use Spring Boot, you can solve it in a more general way with the following property:

spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false

This way you don't need to specify a JsonFormat for each date field you have.

If you also want to customize the date format globally, use the property:

spring.jackson.date-format

Source: https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

Gustavo Passini
  • 2,348
  • 19
  • 25
1

I prevented the conversion by injecting MappingJackson2HttpMessageConverter in the Integration Test

MockMvcBuilders.standaloneSetup(myController).setMessageConverters(mappingJackson2HttpMessageConverter).build();
Pete Ythong
  • 305
  • 5
  • 13
the_tourist
  • 191
  • 2
  • 13