JSON Java 8 LocalDateTime Format in Spring Download

I am having a slight issue with Java 8 LocalDateTime formatting in my Spring boot application. I have no problems with "normal" dates, but the LocalDateTime fields are converted to the following:

"startDate" : { "year" : 2010, "month" : "JANUARY", "dayOfMonth" : 1, "dayOfWeek" : "FRIDAY", "dayOfYear" : 1, "monthValue" : 1, "hour" : 2, "minute" : 2, "second" : 0, "nano" : 0, "chronology" : { "id" : "ISO", "calendarType" : "iso8601" } } 

For now, I would like to convert it to something like:

 "startDate": "2015-01-01" 

My code is as follows:

 @JsonFormat(pattern="yyyy-MM-dd") @DateTimeFormat(iso = DateTimeFormat.ISO.TIME) public LocalDateTime getStartDate() { return startDate; } 

But none of the above annotations work, the date continues to be formatted as described above. Suggestions are welcome!

+94
java json spring-boot java-8 java-time
Apr 29 '15 at 23:08
source share
11 answers

update : Spring Boot 2.x no longer requires this configuration. I wrote a more relevant answer here .




(This is a way to do this before Spring Boot 2.x, it may be useful for people working on the old version of Spring Boot)

I finally found here how to do it. To fix this, I needed another dependency:

 compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.4.0") 

By enabling this dependency, Spring will automatically register the converter for it, as described here . After that, you need to add the following to application.properties:

 spring.jackson.serialization.write_dates_as_timestamps=false 

This will ensure that the correct converter is used, and the dates will be printed in the format 2016-03-16T13:56:39.492

Annotations are only needed if you want to change the date format.

+123
Apr 30 '15 at 5:41
source share

I added the link com.fasterxml.jackson.datatype: jackson-datatype-jsr310: 2.6.1 , and I started to get the date in the following format:

 "birthDate": [ 2016, 1, 25, 21, 34, 55 ] 

which is not what I wanted, but I was approaching. Then I added the following

 spring.jackson.serialization.write_dates_as_timestamps=false 

to the application.properties file, which gave me the correct format that I need.

 "birthDate": "2016-01-25T21:34:55" 
+84
Jan 27 '16 at 7:20
source share

Here it is in Maven, with the property so you can survive between spring download updates

 <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> <version>${jackson.version}</version> </dependency> 
+29
May 13 '16 at 20:53 on
source share

1) Dependence

  compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jsr310', version: '2.8.8' 

2) Annotations with date and time format.

 public class RestObject { private LocalDateTime timestamp; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public LocalDateTime getTimestamp() { return timestamp; } } 

3) Spring Configuration.

 @Configuration public class JacksonConfig { @Bean @Primary public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) { System.out.println("Config is starting."); ObjectMapper objectMapper = builder.createXmlMapper(false).build(); objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); return objectMapper; } } 
+12
Jun 05 '17 at 12:27
source share

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 { /** * Customizing * http://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html * * Defining a @Bean of type Jackson2ObjectMapperBuilder will allow you to customize both default ObjectMapper and XmlMapper (used in MappingJackson2HttpMessageConverter and MappingJackson2XmlHttpMessageConverter respectively). */ @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"

+7
Dec 27 '17 at 6:33
source share

I am writing this answer as a reminder for me.

I combined several answers here, and in the end mine worked with something like this. (I am using SpringBoot 1.5.7 and Lombok 1.16.16)

 @Data public Class someClass { @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) @JsonSerialize(using = LocalDateTimeSerializer.class) @JsonDeserialize(using = LocalDateTimeDeserializer.class) private LocalDateTime someDate; } 
+4
Oct 10 '18 at 6:15
source share

This works great:

Add the dependency:

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

Add annotation:

 @JsonFormat(pattern="yyyy-MM-dd") 

You should now get the correct format.

To use the mapper object, you need to register JavaTime

 ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule()); 
+3
Jul 05 '18 at 19:38
source share

As already mentioned, Spring-Boot will download everything you need (both for web and for starting webflux).

But even better - you do not need to register any modules yourself. Take a look here . Since @SpringBootApplication uses @EnableAutoConfiguration under the hood, this means that JacksonAutoConfiguration will be automatically added to the context. Now, if you look inside JacksonAutoConfiguration , you will see:

  private void configureModules(Jackson2ObjectMapperBuilder builder) { Collection<Module> moduleBeans = getBeans(this.applicationContext, Module.class); builder.modulesToInstall(moduleBeans.toArray(new Module[0])); } 

This guy will be called during the initialization process and will retrieve all the modules that he can find in the class path. (I am using Spring Boot 2.1)

+1
Dec 19 '18 at 17:04 on
source share

I am using Springboot 2.0.6 and for some reason the changes in the yml application do not work. And also I had more requirements.

I tried to create an ObjectMapper and mark it as Primary, but spring loading complained that I already have jacksonObjectMapper as marked as Primary !!

So that’s what I did. I made changes to the internal cartographer.

My Serializer and Deserializer are special - they deal with 'dd / MM / YYYY'; and when deserializing - he tries to use 3-4 popular formats to make sure that I have LocalDate.

 @Autowired ObjectMapper mapper; @PostConstruct public ObjectMapper configureMapper() { mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true); mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, true); mapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true); SimpleModule module = new SimpleModule(); module.addDeserializer(LocalDate.class, new LocalDateDeserializer()); module.addSerializer(LocalDate.class, new LocalDateSerializer()); mapper.registerModule(module); return mapper; } 
+1
Apr 17 '19 at 20:23
source share

@JsonDeserialize(using= LocalDateDeserializer.class) does not work for me with the following dependency.

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

I used the code converter below to deserialize the date in java.sql.Date .

 import javax.persistence.AttributeConverter; import javax.persistence.Converter; @SuppressWarnings("UnusedDeclaration") @Converter(autoApply = true) public class LocalDateConverter implements AttributeConverter<java.time.LocalDate, java.sql.Date> { @Override public java.sql.Date convertToDatabaseColumn(java.time.LocalDate attribute) { return attribute == null ? null : java.sql.Date.valueOf(attribute); } @Override public java.time.LocalDate convertToEntityAttribute(java.sql.Date dbData) { return dbData == null ? null : dbData.toLocalDate(); } } 
0
Sep 27 '18 at 13:55
source share

just use:

 @JsonFormat(pattern="10/04/2019") 

or you can use the template as you like, for example: ('-' in place of '/')

0
Apr 29 '19 at 6:30
source share



All Articles