【笔记】SpringBoot接⼝接收参数是Date类型处理⽅式
背景
最近编写接⼝测试过程中发现,如果后台接收字段类型是Date类型,那么前台直接传字符串类型会直接报如下错误:
org.verter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.Date` from String "2 020-07-08 16:00:00": not a valid representation (error: Failed to parse Date value '2020-07-08 16:00:00': Cannot parse date "2020-07-08 16:00:00": while i t seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null)); nested exception is com.fasterxml.InvalidFormat Exception: Cannot deserialize value of type `java.util.Date` from String "2020-07-08 16:00:00": not a valid representation (error: Failed to parse Date value '2020-07-08 16:00:00': Cannot parse date "2020-07-08 16:00:00": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null) )
at [Source: (PushbackInputStream); line: 3, column: 15] (through reference chain: com.swj.aihouse.ity.LiveSchedule["startTime"])
at org.verter.adJavaType(AbstractJackson2HttpMessageConverter.java:241)
at org.verter.ad(AbstractJackson2HttpMessageConverter.java:223)
情况⼀
如接⼝使⽤POST请求,并@RequestBody 注解接收参数的情况下可以使⽤时间戳的⽅式传递,如startTime:1594193828146,当只需精确到⽇时也可以直接通过字符串"startTime": “2020-07-09”
情况⼆
如直接通过URL传⽇期格式参数,可以使⽤斜线的⽅式传参:startTime=2020/07/09 12:00:00,⽽如⽤这种⽅式会报错,2020-6-24 21:39:58
error parse new情况三
直接通过编写请求参数转换器
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
@Override
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
addDefaultHttpMessageConverters(messageConverters);
for (int i = 0; i < messageConverters.size(); i++) {
HttpMessageConverter<?> mc = (i);
if (mc instanceof MappingJackson2HttpMessageConverter) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
((MappingJackson2HttpMessageConverter) mc).setObjectMapper(objectMapper);
}
converters.add(mc);
}
}
}
情况四
在实体类上使⽤@DateTimeFormat(pattern=“yyyy/MM/dd HH:mm:ss”)转换对应的格式。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。