java - LocalDateTime 将无效日期解析为有效日期并且不抛出任何异常

标签 java spring spring-boot

我在 Spring 的 API 的请求正文中使用 LocalDateTime。

  @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-mm-dd HH:mm:ss")
  @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  @JsonDeserialize(using = LocalDateTimeDeserializer.class)
  @JsonSerialize(using = LocalDateTimeSerializer.class)
  private LocalDateTime createdAt;

当我在请求中输入无效日期时,例如“2020-02-31 00:00:00”,它会自动转换为“2020-02-29 00:00:00”。如果日期无效,我想抛出异常。官方文档中提到它转换为以前的有效日期。
 In some cases, changing the specified field can cause the resulting date-time to become invalid,
 such as changing the month from 31st January to February would make the day-of-month invalid.
 In cases like this, the field is responsible for resolving the date.
 Typically it will choose the previous valid date, 
 which would be the last valid day of February in this example.

最佳答案

您需要为此编写自定义序列化程序。

class CustomLocalDateTimeSerializer extends StdSerializer<LocalDateTime> {
    private static final DateTimeFormatter FORMATTER
            = DateTimeFormatter.ofPattern("yyyy-mm-dd HH:mm:ss");

    ...

    @Override
    public void serialize(LocalDateTime value, JsonGenerator generator, SerializerProvider provider)
            throws IOException, JsonProcessingException {
        // Do your validation using FORMATTER.
        // Serialize the value using generator and provider.
    }
}

然后你可以在你的注释中使用它。

@JsonSerialize(using = CustomLocalDateTimeSerializer.class)

请注意 DateTimeFormatter 格式化/解析无效值时抛出异常。

查看来源 LocalDateTimeSerializer 知道必须做什么。退房 Jackson Date - 10. Serialize Java 8 Date Without Any Extra Dependency有关编写自定义序列化程序的示例。这类似于自定义解串器。

关于java - LocalDateTime 将无效日期解析为有效日期并且不抛出任何异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61172298/

相关文章:

spring - 如何从 H2 中的时间戳列中提取日期

tomcat - 定制Tomcat时: A ServletContext is required to configure default servlet handling

java - 从内部 jar 中的类路径加载资源

java - 假装: Retry depending on response status

java - 如何读取 .7z 扩展文件中的文件内容

java - 在 Rest API 的查询参数中发送 pct (%)

java - 我在 spring/hibernate 中使用什么 mysql 驱动程序?

spring-boot - 如何在界面投影中为以 is 开头的 bool 变量正确设置 getter setter?

Java、unicode 和字体

java - 如何从我从 `java` 目标派生的 Ant 任务中停止 Selenium 服务器?