在使用springboot开发过程中,使用@RequestBody注解接收前端传进的参数时,属性中难免会有日期,但使用@RequestBody注解日期转换会报Cannot deserialize value of type
java.util.Date
from String '2019-xx-xx',下面的方式经过实践可行。在Date类型属性上加上@JsonDeserialize,具体日期格式可自行修改
@JsonDeserialize(using = DateTimeDeserializers.class)private Date insuranceDate;
创建两个类
- DateTimeDeserializers
- DateTimeJsonSerializers
DateTimeJsonSerializers类
public class DateTimeJsonSerializers extends JsonSerializer<Date> {
public static final SimpleDateFormat format=new SimpleDateFormat("yyyy-MM");
@Override
public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws IOException,JsonProcessingException
{
jsonGenerator.writeString(format.format(date));
}
}
DateTimeDeserializers类
public class DateTimeDeserializers extends JsonDeserializer<Date> {
public static final SimpleDateFormat format=new SimpleDateFormat("yyyy-MM");
@Override
public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException,JsonProcessingException
{
try
{
return format.parse(jsonParser.getText());
}
catch(Exception e)
{
throw new RuntimeException(e);
}
}
}