【问题标题】:How to use @DateTimeFormat in springboot in DTO?如何在 DTO 的 Spring Boot 中使用@DateTimeFormat?
【发布时间】:2022-08-12 15:14:25
【问题描述】:

在我的请求 DTO 中,当我尝试使用模式 HHmm 时它不起作用但 HH:mm 有效。

public class RequestDTO {

    @DateTimeFormat(pattern = \"HHmm\")
    private LocalTime companyOfficeHoursStart;

}

下面是我的 MockMVC 测试:

String requestPayload = \"{\\\"companyOfficeHoursStart\\\":\\\"1920\\\"}\";
        RequestBuilder operation = post(\"/bookings\").content(requestPayload)
                .contentType(MediaType.APPLICATION_JSON_VALUE).accept(MediaType.APPLICATION_JSON_VALUE);

我们如何使用嗯嗯格式 ?

标签: spring-boot


【解决方案1】:

@JsonFormat 是 Jackson 注释,Jackson 用于将 POJO 序列化/反序列化到 JSON。 @DateTimeFormat是一个Spring注解,用于设置日期保存到数据库的格式。

对于您的用例,您正在尝试序列化/反序列化 POJO,因此您需要使用 @DateTimeFormat

请参阅此线程以获取更多信息:

https://stackoverflow.com/questions/37871033/spring-datetimeformat-configuration-for-java-time#:~:text=%40JsonFormat%20is%20a%20Jackson%20annotation,rendered%20in%20the%20JSP%20view

【讨论】:

    【解决方案2】:

    【讨论】:

      【解决方案3】:

      当我们希望 DTO 的字段需要使用 Jackson 转换为 JSON/XML 时,我们需要使用 @JsonFormat,而当我们希望将 JSON 转换为 DTO 中的字段时,需要使用 @DateTimeFormat

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-04
        • 1970-01-01
        • 2021-02-10
        • 1970-01-01
        • 1970-01-01
        • 2021-06-25
        • 1970-01-01
        • 2021-08-18
        相关资源
        最近更新 更多