【问题标题】:Spring REST Service converts date-time to numberSpring REST 服务将日期时间转换为数字
【发布时间】:2022-02-02 12:08:47
【问题描述】:

我已经在 swagger 中构建了一个 openapi 模式,其中包含一个字符串类型和格式的字段:日期时间。在示例窗口中,它显示了我

“reportingDateTime”:“2022-02-02T10:56:33.310Z”

。但是当我调用我的服务时,它会响应

“报告日期时间”:1639746778.200000000

我使用 openapi-generator-maven-plugin 版本 5.1.0 生成 spring api 类。生成的响应类有这个字段

@JsonProperty("reportingDateTime")
@org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE_TIME)
私有 OffsetDateTime 报告日期时间;

要获得正确的响应类型需要进行哪些更改?

【问题讨论】:

    标签: java spring openapi openapi-generator


    【解决方案1】:

    Jackson 的默认设置包括将日期格式化为时间戳。这就是你在这里看到的。

    将以下内容添加到您的应用程序属性以将其关闭:

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

    【讨论】:

    • 在我的上下文中不会使用 application.properties。我将 bean 定义从 stackoverflow.com/questions/46278853/… 添加到我的 spring.xml。现在我得到一个大日期对象,而不仅仅是日期时间字符串。
    • 你是说你得到一个对象而不是一个字符串?如果是这样,您需要在对象映射器中显式注册JavaTimeModule 模块。
    【解决方案2】:

    我认为使用DateTimeFormat 进行json 响应可能是错误的。

    尝试阅读这篇文章 - https://www.baeldung.com/jackson-serialize-dates#java-8

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2015-09-17
      相关资源
      最近更新 更多