springboot 日期转化报错
问题场景:
使用Springboot框架搭建服务,传日期参数json参数为2016-08-15 17:00:00这种格式,springboot中不能识别,将其转化为对象对应的日期属性。而是抛出异常信息,提示转换失败。
代码:
传参对应实体类
public class Demo {
private String id;
private Date date;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
controller
@RequestMapping("/demo")
public String demo(@RequestBody Demo demo) {
System.out.println(demo.getId());
return "this is client1";
}
ajax调用使用的postman

请求报错:
{
"timestamp": "2018-09-17T14:01:00.278+0000",
"status": 400,
"error": "Bad Request",
"message": "JSON parse error: Cannot deserialize value of type `java.util.Date` from String \"2018-09-17 21:46:08\": not a valid representation (error: Failed to parse Date value '2018-09-17 21:46:08': Cannot parse date \"2018-09-17 21:46:08\": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null)); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String \"2018-09-17 21:46:08\": not a valid representation (error: Failed to parse Date value '2018-09-17 21:46:08': Cannot parse date \"2018-09-17 21:46:08\": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null))\n at [Source: (PushbackInputStream); line: 3, column: 9] (through reference chain: com.hanggle.eurekaclient.Demo[\"date\"])",
"path": "/demo"
}
错误原因是日期转换失败,由于springboot默认采用jackson,而jackson只能识别以下几种日期格式:
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"; "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; "yyyy-MM-dd"; "EEE, dd MMM yyyy HH:mm:ss zzz"; long类型的时间戳(毫秒时间戳)
不能识别yyyy-MM-dd HH:mm:ss类似格式的数据,所以转换失败。
解决办法有以下几种:
1. 采用long时间戳(毫秒时间戳!!!!)如:1537191968000
2.在传参的对象上加上@JsonFormat注解并且指定时区(此方法治标不治本)
@JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss")
如果项目中使用json解析框架为fastjson框架,则可使用如下解决方法:
在实体字段上使用@JsonFormat注解格式化日期
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss")
3、采用全局处理方式统一处理,推荐这个做法
重写springboot默认转换
参考:https://blog.csdn.net/qq906627950/article/details/79503801
public class MyDateFormat extends DateFormat {
private DateFormat dateFormat;
private SimpleDateFormat format1 = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
public MyDateFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
return dateFormat.format(date, toAppendTo, fieldPosition);
}
@Override
public Date parse(String source, ParsePosition pos) {
Date date = null;
try {
date = format1.parse(source, pos);
} catch (Exception e) {
date = dateFormat.parse(source, pos);
}
return date;
}
// 主要还是装饰这个方法
@Override
public Date parse(String source) throws ParseException {
Date date = null;
try {
// 先按我的规则来
date = format1.parse(source);
} catch (Exception e) {
// 不行,那就按原先的规则吧
date = dateFormat.parse(source);
}
return date;
}
// 这里装饰clone方法的原因是因为clone方法在jackson中也有用到
@Override
public Object clone() {
Object format = dateFormat.clone();
return new MyDateFormat((DateFormat) format);
}
}
@Configuration
public class WebConfig { @Autowired
private Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder; @Bean
public MappingJackson2HttpMessageConverter MappingJsonpHttpMessageConverter() { ObjectMapper mapper = jackson2ObjectMapperBuilder.build(); // ObjectMapper为了保障线程安全性,里面的配置类都是一个不可变的对象
// 所以这里的setDateFormat的内部原理其实是创建了一个新的配置类
DateFormat dateFormat = mapper.getDateFormat();
mapper.setDateFormat(new MyDateFormat(dateFormat)); MappingJackson2HttpMessageConverter mappingJsonpHttpMessageConverter = new MappingJackson2HttpMessageConverter(
mapper);
return mappingJsonpHttpMessageConverter;
} }
参考资料:
https://blog.csdn.net/pp_fzp/article/details/79588374
https://blog.csdn.net/qq906627950/article/details/79503801
springboot 日期转化报错的更多相关文章
- Springboot数据库连接池报错的解决办法
Springboot数据库连接池报错的解决办法 这个异常通常在Linux服务器上会发生,原因是Linux系统会主动断开一个长时间没有通信的连接 那么我们的问题就是:数据库连接池长时间处于间歇状态,导致 ...
- Java类型转化报错
Java类型转化报错 报错如下: java.lang.ClassCastException:java.util.HashMap cannot be cast to java.util.List.
- Springboot 启动文件报错,原因是@ComponentScan写成了@ComponentScans
Springboot 启动文件报错,原因是@ComponentScan写成了@ComponentScans
- springboot测试启动报错java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
springboot测试启动报错: java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you ne ...
- springboot项目启动报错Failed to configure a DataSource: 'url' attribute is not specified and no embedde
springboot项目启动报错Failed to configure a DataSource: 'url' attribute is not specified and no embedde 创建 ...
- Springboot整合Elasticsearch报错availableProcessors is already set to [4], rejecting [4]
Springboot整合Elasticsearch报错 今天使用SpringBoot整合Elasticsearch时候,相关的配置完成后,启动项目就报错了. nested exception is j ...
- SpringBoot集成MybatisPlus报错
SpringBoot集成MybatisPlus报错 启动的时候总是报如下错误: java.lang.annotation.AnnotationFormatError: Invalid default: ...
- Springboot 之 启动报错-Cannot determine embedded database driver class for database type NONE
Springboot 之 启动报错-数据库 springboot项目在启动时,报如下错误: Error starting ApplicationContext. To display the auto ...
- Springboot项目启动报错,提示Cannot determine embedded database driver class for database type NONE
我在springboot项目里面引入了数据库的配置: <dependency> <groupId>org.mybatis.spring.boot</groupId> ...
随机推荐
- Daily Scrum (2015/11/4)
因为距离部署的时间临近,而之前我们的进度偏慢.这天晚上我们大多数成员几乎所有时间都用在了这个项目上,成果还算令人满意. 成员 今日任务 时间 明日任务 符美潇 1.修复了一个BUG,此BUG会导致所爬 ...
- Structs2笔记①--structs的背景、structs2框架的意义、第一个helloworld
Struts2的背景 由出色稳定的框架struts1和webwork框架整合而来的 吸取了两大框架的优点 提高了开发的效率和规范性 更好的实现了MVC架构 解除了与servlet的强耦合性 使用str ...
- window 窗口编辑
package com.chuangkohua; import java.awt.FileDialog; import java.awt.FlowLayout; import java.awt.Fra ...
- tomcat启动问题排查
遇到tomcat错误时不一定是tomcat的配置问题,还有可能是项目的配置问题.检查下xml的servlet配置是不是出了问题. tomcat8.0使用注解的方式帮我注册了servlet了,这时候已经 ...
- PMS---团队展示
点我查看作业原题 [队名] PMS(一群pm) [拟做的团队项目描述] 基于监控场景的视频摘要与人车检测跟踪系统 A system, under monitor scene, for video su ...
- 信安实践——CSRF攻击与防御
1.实验原理 CSRF(Cross-Site Request Forgery,跨站点伪造请求)是一种网络攻击方式,该攻击可以在受害者毫不知情的情况下以受害者名义伪造请求发送给受攻击站点,从而在未授权的 ...
- NodeJs异步的执行过程
我这里写了一个代码片段,用来模拟一个嵌套的异步过程,下面我总结了下这段代码的执行顺序var fs = require("fs"); fs.stat('a.txt',callback ...
- 七类网线 支持10gb/s的速度的计算方法
0. 说明 我是数学白痴, 只是套了下公式... 1. 七类网线的参数: 七类线 ISO/IEC 7类/F级标准 中最新的一种双绞线,它主要为了适应万兆位以太网技术的应用和发展.但它不再是一种非屏蔽双 ...
- ES6 常用1
( (1)交换变量的值 ) [x, y] = [y, x]; ( (2)从函数返回多个值 // 返回一个数组function example() { return [1, 2, 3]; } var [ ...
- NULL,"",String.Empty三者在C#中的区别
(1)NULLnull 关键字是表示不引用任何对象的空引用的文字值.null 是引用类型变量的默认值.那么也只有引用型的变量可以为NULL,如果int i=null,的话,是不可以的,因为Int是值类 ...