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> ...
随机推荐
- OO终章--总结博客
一.测试与正确性论证的比较 从方法上看,测试是使用大量测试样例来覆盖测试代码,从而能够检测代码的实现是否正确,功能是否完善.而正确性论证是使用代码的规格和逻辑进行严密的推论和证明,从而验证代码的实现正 ...
- Structs2笔记③--局部类型转换案例
Structs2的类型转换-局部类型转换 Ognl强大的表达式语言,在导入项目的时候我们导入了ognl.jar包,内有TypeConverter类,struct主要依赖于他进行类型转换. 例子 i ...
- “吃神么,买神么”的第一个Sprint计划(第四天)
“吃神么,买神么”项目Sprint计划 ——5.24 星期日(第四天)立会内容与进度 摘要:logo做出来了,但是在立会展示时遭到反对,不合格,重新设计.(附上失败的logo图) 目前搜索栏出来了, ...
- 【搜索】POJ-3669 BFS
一.题目 Description Bessie hears that an extraordinary meteor shower is coming; reports say that these ...
- 使用java开发微信公众平台(1)
目录 开发服务器 域名验证 获取access_token 自定义菜单 个人账号不能定义url访问服务器,使用测试号就不用认证添加url了,进入公众平台测试账号 开发服务器 域名验证 进入公众平台测试账 ...
- Beta 冲刺 (4/7)
队名:日不落战队 安琪(队长) 过去两天完成了那些任务 完善已完成的界面. 接下来的任务 建立和上传收藏夹. 还剩下的任务 完善手写涂鸦. 遇到的困难 明天考试,准备通宵中. 有哪些收获和疑问 无. ...
- 弹出提示框的方式——java
1.显示一个错误对话框,该对话框显示的 message 为 'alert': JOptionPane.showMessageDialog(null, "alert", " ...
- 用vue实现省市县三级联动
我真的没想到这个会困扰到我.最开始以为,不就是直接找个简单的插件就实现了吗,jquery插件找了几个,都没有达到目的. 需求是这样的: 点击input框,弹出一个popup,然后可以滚动选择省,市,县 ...
- Selenium_RC环境配置
上一篇里,对Selenium IDE自动录制的脚本进行了一下分析,按照前两篇的操作,很明显,新建的 那个Test.py文件是不能运行的.关键问题在于1.没有装Python:2.没有装Selenium_ ...
- teamcity和jmeter结合进行接口自动化测试
(1)从teamcity官网下载jmeter插件:https://teamcity.jetbrains.com/repository/download/TeamCityPluginsByJetBrai ...