客户端传日期格式字段(String),服务端接口使用java.util.Date类型接收报错问题

问题演示

  1. 演示代码

服务端接口代码

	@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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值