JSON Java 8 LocalDateTime format in Spring Boot

2019-01-03 09:39发布

I'm having a small problem with formatting a Java 8 LocalDateTime in my Spring Boot Application. With 'normal' dates I have no problem, 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"
    }
  }

While I would like convert it to something like:

"startDate": "2015-01-01"

My code looks like this:

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

But either of the above annotations don't work, the date keeps getting formatted like above. Suggestions welcome!

9条回答
ら.Afraid
2楼-- · 2019-01-03 10:01

Writing this answer as a reminder for me as well.

I combined several answers here and in the end mine worked with something like these. (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;

}
查看更多
Evening l夕情丶
3楼-- · 2019-01-03 10:01

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

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

I have used the below code converter to deserialize the date into a 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();
    }
}
查看更多
趁早两清
4楼-- · 2019-01-03 10:03

update: Spring Boot 2.x doesn't require this configuration anymore. I've hopefully given a more up to date answer here: https://stackoverflow.com/a/53848020/323221


(This is the way of doing it before Spring Boot 2.x, it might be useful for people working on an older version of Spring Boot)

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

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

By including this dependency, Spring will automatically register a 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 a correct converter is used, and dates will be printed in the format of 2016-03-16T13:56:39.492

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

查看更多
贪生不怕死
5楼-- · 2019-01-03 10:09

This work fine:

Add the dependency:

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

Add the annotation:

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

Now, you must get the correct format.

To use object mapper, you need register the JavaTime

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
查看更多
Melony?
6楼-- · 2019-01-03 10:11

As already mentioned, spring-boot will fetch all you need (for both web and webflux starter).

But what's even better - you don't need to register any modules yourself. Take a look here. Since @SpringBootApplication uses @EnableAutoConfiguration under the hood, it means JacksonAutoConfiguration will be added to the context automatically. 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 fella will be called in the process of initialization and will fetch all the modules it can find in the classpath. (I use Spring Boot 2.1)

查看更多
在下西门庆
7楼-- · 2019-01-03 10:19

Here it is in maven, with the property so you can survive between spring boot upgrades

<dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-jsr310</artifactId>
        <version>${jackson.version}</version>
</dependency>
查看更多
登录 后发表回答