我有一个spring应用程序
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.11.0</version>
</dependency>
我可以从前端接收带有日期字段的json对象,可以有前导零,也可以没有前导零(1991-2-3或1991-02-03)。我知道,用 yyyy-M-d
用于反序列化输入:
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class MyDto implements Serializable{
//other fields...
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-M-d")
LocalDate date;
}
问题是它总是返回没有填充零的日期,例如。 1991-2-3
. 有没有一种方法可以让它接受任何一种模式,但总是序列化以包含零,例如。 1991-02-03
?
1条答案
按热度按时间6qftjkof1#
我发现可以实现自定义反序列化程序来代替使用
@JsonFormat
,使用DateTimeFormatter
:和
然后,只需在注解中使用自定义反序列化程序