2

Consider this Spring MVC controller started using Spring Boot:

@RequestMapping("/foo")
public Foo get() {
    return new Foo();
}

public class Foo {
    @Getter
    @Setter
    private ZonedDateTime time = ZonedDateTime.now();
}

I want to serialize the Foo object with Jackson JSR-310 module. This dependency is on classpath:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

I also have jackson configuration in my application.properties:

spring.jackson.serialization.write-dates-as-timestamps=false

According to jackson documentation it should convert it to ISO datetime format, but I'm still getting a timestamp value...

{
  time: 1508867114.796
}

I have noticed that inside ZonedDateTimeSerializer:

@Override
public void serialize(ZonedDateTime value, JsonGenerator generator, SerializerProvider provider) throws IOException {
    if (!useTimestamp(provider)) {
        if (shouldWriteWithZoneId(provider)) {
            // write with zone
            generator.writeString(DateTimeFormatter.ISO_ZONED_DATE_TIME.format(value));
            return;
        }
    }
    super.serialize(value, generator, provider);
}

useTimestamp(provider) is evaluated to true, so the property in application.properties is ignored.

Any ideas what can be wrong with my code?

jantobola
  • 688
  • 2
  • 10
  • 28
  • If you don't want timestamp,ZonedDateTimeSerializer is not necessary.if not,show more details about useTimestamp and shouldWriteWithZoneId – dai Oct 25 '17 at 03:01

1 Answers1

0

You were almost there. If you annotate your field time of your DTO Foo with

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")

your approach will be working. You'll get the result:

{
    "time": "2019-12-07T17:05:59.000+0400"
}

In current Spring Boot versions (2.2.x) you can omit your application.properties configuration entry spring.jackson.serialization.write-dates-as-timestamps=false, because it is default now.

ThirstForKnowledge
  • 1,245
  • 1
  • 10
  • 27