如何让 Jackson @JsonFormat 的秒数可选?

How to make seconds optional for Jackson @JsonFormat?

I read that one can specify the pattern attribute of @JsonFormat so that a specific part of the date or time is optional. I would like the seconds of a time to be optional. So that values like "22:10" and "22:10:00" would be parsed. I had a look at the documentation and figured that the "s" is the correct pattern letter 秒。

@JsonProperty
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "HH:mm[.ss]")
private LocalTime test5;

我认为如果我将两个“s”放在方括号中并在它们前面加上一个点,事情应该会起作用。但是,只接受值“22:10”。如果我传递一个像“22:10:00”这样的值,我会收到以下错误:

Cannot deserialize value of type `java.time.LocalTime` from String "22:10:00": Text '22:10:00' could not be parsed, unparsed text found at index 5

如何仅使用注释使秒数可选?

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "HH:mm[.ss]")

在这一行中,您使用的秒格式是 '.ss'。 如果秒数前面有“:”,那么您需要使用这种模式:"HH:mm[:ss]"