Jackson Date Format for OffsetDateTime in Spring Download

I am trying to infer OffsetDateTime from my Spring application and have the following properties in my application:

spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false spring.jackson.date-format=yyyy-MM-dd'T'HH:mm 

However, when the date returns, it is formatted as

 "2017-01-30T16:55:00Z" 

How to properly set date format in spring application?

+11
source share
5 answers

So, I managed to find a solution, but if you have an alternative, submit it.

As a result, I created a new primary ObjectMapper bean and registered a new module using a special serializer for OffsetDateTime . Here I can set my date format using java.time.format.DateTimeFormatter . I also had to register a JavaTimeModule with my mapper.

 @Configuration public class JacksonOffsetDateTimeMapper{ @Primary @Bean public ObjectMapper objectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JavaTimeModule()); SimpleModule simpleModule = new SimpleModule(); simpleModule.addSerializer(OffsetDateTime.class, new JsonSerializer<OffsetDateTime>() { @Override public void serialize(OffsetDateTime offsetDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeString(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(offsetDateTime)); } }); objectMapper.registerModule(simpleModule); return objectMapper; } } 
+10
source

Have you added jackson-datatype-jsr310 to your dependencies?

+3
source
  • Add jackson-datatype-jsr310 to your dependencies
  • Add to application.properties:

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

You'll get:

 "lastUpdated": "2017-07-16T19:17:57.689Z" 
+1
source

Have you tried to put @JsonFormat(pattern="dd/MM/yyyy HH:mm:ss Z") in front of your field?

 @JsonProperty("timestamp") @JsonFormat(pattern="yyyy-MM-dd'T'HH:mm") private OffsetDateTime timestamp; 

I think you will get:

 2017-01-30'T'16:55 
+1
source

The Spring property does not work for me as well. Setting a property on ObjectMapper works for me, though.

 objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); 
0
source

Source: https://habr.com/ru/post/1014463/


All Articles