前端GET请求url参数,携带了fillInDay这个日期值:
?fillInDay=2024-04-17¤t=1&size=20&roleCodes=10000
DTO的属性,只是添加了JsonFormat注解:
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private LocalDate fillInDay;
前端看到的报错信息
Validation failed for object=‘equipmentMonitoringFillInDTO’. Error count: 1
后端完整报错提示:
Field error in object ‘equipmentMonitoringFillInDTO’ on field ‘fillInDay’: rejected value [2024-04-17]; codes [typeMismatch.equipmentMonitoringFillInDTO.fillInDay,typeMismatch.fillInDay,typeMismatch.java.time.LocalDate,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [equipmentMonitoringFillInDTO.fillInDay,fillInDay]; arguments []; default message [fillInDay]]; default message [Failed to convert property value of type ‘java.lang.String’ to required type ‘java.time.LocalDate’ for property ‘fillInDay’; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@com.fasterxml.jackson.annotation.JsonFormat java.time.LocalDate] for value ‘2024-04-17’; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2024-04-17]]]
解决方案
看着原因是因为日期参数格式和springboot默认解析格式不对应,自己指定日期格式就可以,加上注解@DateTimeFormat并指定日期格式就可以
@DateTimeFormat注解是来自这个包,不要导错:org.springframework.format.annotation.DateTimeFormat
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate fillInDay;