I found another solution that you can convert to any format and apply LocalDateTime to all data types, and you do not need to specify @JsonFormat over each LocalDateTime data type. First add the dependency:
<dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> </dependency>
Add the following bean:
@Configuration public class Java8DateTimeConfiguration { @Bean public Module jsonMapperJava8DateTimeModule() { val bean = new SimpleModule(); bean.addDeserializer (ZonedDateTime.class, new JsonDeserializer<ZonedDateTime>() { @Override public ZonedDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { return ZonedDateTime.parse(jsonParser.getValueAsString(), DateTimeFormatter.ISO_ZONED_DATE_TIME); } }); bean.addDeserializer(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() { @Override public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { return LocalDateTime.parse(jsonParser.getValueAsString(), DateTimeFormatter.ISO_LOCAL_DATE_TIME); } }); bean.addSerializer(ZonedDateTime.class, new JsonSerializer<ZonedDateTime>() { @Override public void serialize( ZonedDateTime zonedDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeString(DateTimeFormatter.ISO_ZONED_DATE_TIME.format(zonedDateTime)); } }); bean.addSerializer(LocalDateTime.class, new JsonSerializer<LocalDateTime>() { @Override public void serialize( LocalDateTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeString(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(localDateTime)); } }); return bean; } }
in your configuration file add the following:
@Import(Java8DateTimeConfiguration.class)
This will serialize and deserialize all the LocalDateTime and ZonedDateTime properties if you use the objectMapper created by Spring.
The format you received for ZonedDateTime: "2017-12-27T08: 55: 17.317 + 02: 00 [Asia / Jerusalem]" for LocalDateTime: "2017-12-27T09: 05: 30.523"
Ida Amit Dec 27 '17 at 6:33 2017-12-27 06:33
source share