我有一个棱角分明的应用程序,可以向我发送类似dd / MM / yyyy和类似yyyy-MM-dd的日期。 我如何使用@JsonFormat接受两种模式? 目前我只使用:
@Temporal(TemporalType.DATE)
@JsonFormat(pattern="dd/MM/yyyy")
private Date hireDate;
当我收到的日期格式为dd / MM / yyyyy时有效,但是当日期格式为yyyy-MM-dd时我有json解析错误
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.Date` from String "2018-10-26": expected format "dd/MM/yyyy";
答案 0 :(得分:1)
json格式接受单个参数。您可以改用正则表达式或自定义反序列化器。
模式:
@Temporal(TemporalType.DATE)
@JsonFormat(pattern="^(\\d{2}/\\d{2}/\\d{4})|^(\\d{4}-\\d{2}-\\d{2})"
private Date hireDate;
自定义反序列化器:(https://stackoverflow.com/a/5598277)
@JsonDeserialize(using = CustomJsonDateDeserializer.class)
P.S:请注意,我提供的正则表达式模式不包含错误月份或错误天数的日期验证。因此,我建议您使用自定义反序列化器或要求呼叫者以UTC时间戳格式发送。