问题场景:

使用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 日期转化报错的更多相关文章

  1. Springboot数据库连接池报错的解决办法

    Springboot数据库连接池报错的解决办法 这个异常通常在Linux服务器上会发生,原因是Linux系统会主动断开一个长时间没有通信的连接 那么我们的问题就是:数据库连接池长时间处于间歇状态,导致 ...

  2. Java类型转化报错

    Java类型转化报错 报错如下: java.lang.ClassCastException:java.util.HashMap cannot be cast to java.util.List.

  3. Springboot 启动文件报错,原因是@ComponentScan写成了@ComponentScans

    Springboot 启动文件报错,原因是@ComponentScan写成了@ComponentScans

  4. 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 ...

  5. 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 创建 ...

  6. Springboot整合Elasticsearch报错availableProcessors is already set to [4], rejecting [4]

    Springboot整合Elasticsearch报错 今天使用SpringBoot整合Elasticsearch时候,相关的配置完成后,启动项目就报错了. nested exception is j ...

  7. SpringBoot集成MybatisPlus报错

    SpringBoot集成MybatisPlus报错 启动的时候总是报如下错误: java.lang.annotation.AnnotationFormatError: Invalid default: ...

  8. Springboot 之 启动报错-Cannot determine embedded database driver class for database type NONE

    Springboot 之 启动报错-数据库 springboot项目在启动时,报如下错误: Error starting ApplicationContext. To display the auto ...

  9. Springboot项目启动报错,提示Cannot determine embedded database driver class for database type NONE

    我在springboot项目里面引入了数据库的配置: <dependency> <groupId>org.mybatis.spring.boot</groupId> ...

随机推荐

  1. iOS学习资源搜集

    swift 2.0 新的开始 iOS7初学者入门 斯坦福大学公开课:iOS 8开发 苹果官方开发 中文 iOS/Mac 开发博客列表    git

  2. Journal entry of the eleventh chapter to chapter twelfth

    第十一章:正如很多人一样,觉得软件工程这个课程好像没什么用,感觉提高不了自己的写代码能力,学的都是理论知识,好像对于我们这种技术类的专业离得有点远,是这样的吗? 第十二章:每样东西都没有完美的,即使我 ...

  3. 团队作业7——第二次项目冲刺(Beta版本12.04——12.07)

    1.当天站立式会议照片 本次会议在5号公寓3楼召开,本次会议内容:①:熟悉每个人想做的模块.②:根据项目要求还没做的完成. 2.每个人的工作 经过会议讨论后确定了每个人的分工 组员 任务 陈福鹏 实现 ...

  4. Effective Modern C++翻译(5)-条款4:了解如何观察推导出的类型

    条款4:了解如何观察推导出的类型 那些想要知道编译器推导出的类型的人通常分为两种,第一种是实用主义者,他们的动力通常来自于软件产生的问题(例如他们还在调试解决中),他们利用编译器进行寻找,并相信这个能 ...

  5. #Leetcode# 451. Sort Characters By Frequency

    https://leetcode.com/problems/sort-characters-by-frequency/ Given a string, sort it in decreasing or ...

  6. IPV6 简单总结

    1. 转帖别人的内容 来源:https://www.2cto.com/net/201112/114937.html 2. 本地用IPV6单播地址 (包括链路本地单播地址 和 站点本地单播地址) 2.1 ...

  7. PHP中的PEAR是什么?

    PEAR也就是为PHP扩展与应用库(PHP Extension and Application Repository),它是一个PHP扩展及应用的一个代码仓库. 补充:php中扩展pecl与pear ...

  8. SpringBoot(八)_springboot集成swagger2

    swagger是一个功能强大的api框架,它的集成非常简单,不仅提供了在线文档的查阅,而且还提供了在线文档的测试. (1) 引入依赖,我们选择现在最新的版本 <dependency> &l ...

  9. [BZOJ1559]密码 AC自动机+状压

    问题 K: [JSOI2009]密码 时间限制: 1 Sec  内存限制: 64 MB 题目描述 众所周知,密码在信息领域起到了不可估量的作用.对于普通的登陆口令,唯一的破解 方法就是暴力破解一逐个尝 ...

  10. STL Set和multiset 容器

    STL Set和multiset 容器 set/multiset的简介 set是一个集合容器,其中所包含的元素是唯一的,集合中的元素按一定的顺序排列. 元素插入过程是按排序规则插入,所以不能指定插入位 ...