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> ...
随机推荐
- Scrum Meeting 11.05
成员 今日任务 明日计划 用时 徐越 代码移植 学习ListView+simpleAdapter,actionBar.阅读并修改前端代码 4h 赵庶宏 服务器配置,代码移植 构建后端数据库,进行完善 ...
- 20162327WJH第一次实验——线性结构
20162327WJH第一次实验--线性结构 实 验 报 告 实 验 报 告 课程:程序设计与数据结构 班级: 1623 姓名: 王旌含 学号:20162327 成绩: 2分 指导教师:娄嘉鹏 王志强 ...
- 安卓开发神器vysor+adb wifi
准备: 1.vysor需要FQ从google应用商店下载,装在google上,目前知道的免费的vysor的作用是电脑显示手机屏幕并且能操控手机. 步骤:FQ后就能下载了,FQ方法不赘述.
- Beta Scrum Day 3 — 听说
听说
- week4d:个人博客作业
7,程序结果的显示 1,界面 2,选第一选项. 3,输入3个数后. 4,选择第一个. 5,输入第4个数字. 6,再次进行一轮游戏. 7,选择是否要看历史记录. 8,进入下一轮游戏. 9,开始第二轮数字 ...
- Head First Java & static
- Redis内存回收:LRU算法
Redis技术交流群481804090 Redis:https://github.com/zwjlpeng/Redis_Deep_Read Redis中采用两种算法进行内存回收,引用计数算法以及LRU ...
- Week3结对项目-数独游戏
题目要求 1)在文章开头给出Github项目地址.(1') 2)在开始实现程序之前,在下述PSP表格记录下你估计将在程序的各个模块的开发上耗费的时间.(0.5') 3)看教科书和其它资料中关于Info ...
- Concise and clear CodeForces - 991F(dfs 有重复元素的全排列)
就是有重复元素的全排列 #include <bits/stdc++.h> #define mem(a, b) memset(a, b, sizeof(a)) using namespace ...
- PowerDesigner在生成SQL时报错Generation aborted due to errors detected during the verification of the mod
一.本章节要用到 ODBC连接数据库直接创建表,请先创建连接库的ODBC 请参考 新建 http://www.cnblogs.com/wdw31210/p/7580286.html 二.生成 去 ...