【问题标题】:Spring Json parse dateSpring Json 解析日期
【发布时间】:2018-10-26 08:15:28
【问题描述】:

我有一个 Angular 应用程序,它会向我发送一个日期,例如 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";

【问题讨论】:

    标签: json spring spring-boot spring-data


    【解决方案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 时间戳格式发送。

    【讨论】:

      猜你喜欢
      • 2012-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-17
      相关资源
      最近更新 更多