Spring Boot 中的 JSON Java 8 LocalDateTime 格式 [英] JSON Java 8 LocalDateTime format in Spring Boot

查看:52
本文介绍了Spring Boot 中的 JSON Java 8 LocalDateTime 格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Spring Boot 应用程序中格式化 Java 8 LocalDateTime 时遇到了一个小问题.使用正常"日期我没有问题,但 LocalDateTime 字段转换为以下内容:

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"

我的代码如下:

@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!

推荐答案

update:Spring Boot 2.x 不再需要此配置.我写了 一个更新在这里回答.

update: Spring Boot 2.x doesn't require this configuration anymore. I've written a more up to date answer here.

(这是在 Spring Boot 2.x 之前的做法,它可能对使用旧版本 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")

通过包含此依赖项,Spring 将自动为其注册转换器,如这里.之后,您需要在 application.properties 中添加以下内容:

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

这将确保使用正确的转换器,日期将以2016-03-16T13:56:39.492

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.

这篇关于Spring Boot 中的 JSON Java 8 LocalDateTime 格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆