gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:21:04 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com