Field error in object 'xxx' on field 'xxx': rejected value [xxx]

Lin2J
2021-03-31 / 0 评论 / 492 阅读
温馨提示:
本文最后更新于2021-03-31,若内容或图片失效,请留言反馈。

GET 请求中的日期参数在使用 @JsonFormat 格式化时间后报错

@ApiModelProperty("发布时间-开始")
@JsonFormat(pattern = DatePattern.NORM_DATE_PATTERN,timezone = Constants.GMT8)
private Date startPublishTime;
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'algoInfoQo' on field 'startPublishTime': rejected value [2021-03-29]; codes [typeMismatch.algoInfoQo.startPublishTime,typeMismatch.startPublishTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [algoInfoQo.startPublishTime,startPublishTime]; arguments []; default message [startPublishTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'startPublishTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@io.swagger.annotations.ApiModelProperty @com.alibaba.fastjson.annotation.JSONField java.util.Date] for value '2021-03-29'; nested exception is java.lang.IllegalArgumentException]
	at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:164) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]

增加 @DateTimeFormat 标注即可。

@ApiModelProperty("发布时间-开始")
@DateTimeFormat(pattern = DatePattern.NORM_DATE_PATTERN, iso = DateTimeFormat.ISO.DATE)
@JsonFormat(pattern = DatePattern.NORM_DATE_PATTERN,timezone = Constants.GMT8)
private Date startPublishTime;