问题场景:

使用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. The user survey(用户调查)

    在周末,我们找了一些人来进行了一个调查,鉴于选择困难,我们只找到了几个真正的小学生,没有找到家长,其余那些都是找大学生来做调查的,我们和他们说,让他们把自己的立场看成是小学生或家长.下面是我们整理出来 ...

  2. grep文本处理工具

    grep是一款文本过滤工具,基于正则表达式进行模式匹配sed:stream editor 流编辑器awk:linux上实现为gawk,文本报告生成器(格式化文本)文本搜索工具,根据用户指定的模式,对目 ...

  3. [微软官网]SQLSERVER的版本信息

    来源:https://docs.microsoft.com/zh-cn/sql/sql-server/editions-and-components-of-sql-server-2017?view=s ...

  4. [转帖] Linux buffer 和 cache相关内容

    Linux中Buffer/Cache清理 Lentil2018年9月6日 Linux中的buff/cache可以被手动释放,释放缓存的代码如下: https://lentil1016.cn/linux ...

  5. [转帖]TLS 版本问题

    转帖 From https://www.cnblogs.com/xjnotxj/p/7252043.html 一.环境: CentOS 6.8nginx 1.6.0php 7.0.10 二.背景 最近 ...

  6. (很难啊)如何实时获取DBGrid 中当前单元格输入的内容? [问题点数:100分,结帖人yifawu100]

    如何获取DBGrid 中当前单元格输入的内容? 还没输入完成,我想实时获取 Cell中的内容,以便作其他处理,用什么事件呢? 所以Field的Onchange事件是没用的. DBGrid1.Selec ...

  7. app流畅度测试--使用FPS Meter

    1.FFPS Meter是一款非常实用的小软件,能够用数字实时显示安卓界面的每秒帧数,非常直观.此外,FPS Meter还可以显示最大帧数.最小帧数以及平均帧数,用来评价安卓流畅度极具价值.由于涉及到 ...

  8. Dapper 事务处理

    例子: using (var connection = GetOpenConnection()) using (var transaction = connection.BeginTransactio ...

  9. hibernate关联关系

    hibernate是一个强大的ORM框架,为了使用面向对象的方式管理数据库,hibernate提供了4中关系设置: 1.一对一 (one-to-one) 2.一对多 (one-to-many) 3.多 ...

  10. C++模板编程中只特化模板类的一个成员函数

    模板编程中如果要特化或偏特化(局部特化)一个类模板,需要特化该类模板的所有成员函数.类模板中大多数成员函数的功能可能是一模一样的,特化时我们可能只需要重新实现1.2个成员函数即可.在这种情况下,如果全 ...