客户端传日期格式字段(string),服务端接口使用java.util.Date类型接收报错问题
问题演示
- 演示代码
服务端接口代码
@PostMapping("/binder")
@ResponseBody
public String binderTest(TestEntity te) {
return te.getBirthDay().toString() ;
}
以上接口中的实体TestEntity
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
@Data
public class TestEntity {
private String name;
private String addr;
private Date birthDay;
}
TestEntity中的字段birthDay为Date类型
客户端演示使用PostMan
第1种:客户端以URL拼接的方式传值
后台报错:
Field error in object 'testEntity' on field 'birthDay': rejected value [2024-02-09 22:22:33]; codes
[typeMismatch.testEntity.birthDay,typeMismatch.birthDay,typeMismatch.java.util.Date,typeMismatch];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes
[testEntity.birthDay,birthDay]; arguments []; default message [birthDay]]; default message [Failed to convert
property value of type 'java.lang.String' to required type 'java.util.Date' for property 'birthDay'; nested exception
is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String]
to type [java.util.Date] for value '2024-02-09 22:22:33'; nested exception is
java.lang.IllegalArgumentException]]
第2种:客户端以body中的form-data方式提交
后台报错:
Field error in object 'testEntity' on field 'birthDay': rejected value [2024-02-07]; codes
[typeMismatch.testEntity.birthDay,typeMismatch.birthDay,typeMismatch.java.util.Date,typeMismatch];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes
[testEntity.birthDay,birthDay]; arguments []; default message [birthDay]]; default message [Failed to convert
property value of type 'java.lang.String' to required type 'java.util.Date' for property 'birthDay'; nested exception
is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String]
to type [java.util.Date] for value '2024-02-07'; nested exception is java.lang.IllegalArgumentException]]
第3种 客户端以Body中的json方式提交
这里需要先在接口中,添加注解@RequestBody,接口变成如下:
@PostMapping("/binder")
@ResponseBody
public String binderTest(@RequestBody TestEntity te) {
return te.getBirthDay().toString() ;
}
以上日期格式是 yyyy-MM-dd (2024-06-08),可以成功!
但是,将格式变成yyyy-MM-dd HH:mm:ss,就不行了,见如下:
后台报错:
JSON parse error: Cannot deserialize value of type `java.util.Date` from String "2024-06-08 22:11:33": not a
valid representation (error: Failed to parse Date value '2024-06-08 22:11:33': Cannot parse date "2024-06-08
22:11:33": while it seems to fit format 'yyyy-MM-dd