SpringMvc Json LocalDateTime 互转,form urlencoded @ModelAttribute 转换
JDK8 的LocalDate 系列日期API ,比Date 或者 Calendar 都好用很多,但是在SpringMvc 自动装配会有点小问题
会导致抛出类似异常
default message [Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDateTime' for property 'createDate';
nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type ... for value '2017-11-03';
nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value
解决方法 1 注意 @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") form 或者url 传过来的 日期必须严格根据此 格式,实在没有的,需要在前端补全格式,否则依然会抛出以上异常
@JsonDeserialize(using = LocalDateTimeDeserializer.class) //application/json
@JsonSerialize(using = LocalDateTimeSerializer.class) //application/json
//LocalDateTime
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") //application/x-www-form-urlencoded
private LocalDateTime createDate;
//LocalDate
@DateTimeFormat(pattern = "yyyy-MM-dd") //application/x-www-form-urlencoded
private LocalDate createDate;
解决方法 2 此方法只处理json 不能处理 application/x-www-form-urlencoded 也就是说 @ModelAttribute 的时候还是需要 @DateTimeFormat 注解
继承 WebMvcConfigurerAdapter
private static class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> { private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); @Override
public void serialize(LocalDateTime value, JsonGenerator jgen, SerializerProvider provider)
throws IOException {
jgen.writeString(dateTimeFormatter.format(value));
} } private static class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> { @Override
public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
String result = StringDeserializer.instance.deserialize(jsonParser, deserializationContext);
return LocalDateTimeUtil.UDateToLocalDateTime(DateUtil.parseDate(DateUtil.C_TIME_PATTON_DEFAULT,result));
}
}
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
for (HttpMessageConverter converter : converters) {
if (converter instanceof MappingJackson2HttpMessageConverter) {
ObjectMapper objectMapper = ((MappingJackson2HttpMessageConverter) converter).getObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer());
module.addDeserializer(LocalDateTime.class,new LocalDateTimeDeserializer());
objectMapper.registerModule(module);
}
}
}
2018年3月12日 15:09:28 对 解决方法 2 的补充 在继承WebMvcConfigurerAdapter的配置类中注册转换器 可以支持application/x-www-form-urlencoded 的自动装配
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new DateConverter());
registry.addConverter(new LocalDateConverter());
registry.addConverter(new LocalDateTimeConverter());
} public static class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
if (!NumberUtils.isDigits(source))
return null;
Long milli = NumberUtils.createLong(source);
return new Date(milli);
}
} public static class LocalDateTimeConverter implements Converter<String, LocalDateTime> {
@Override
public LocalDateTime convert(String source) {
if (!NumberUtils.isDigits(source))
return null;
Long milli = NumberUtils.createLong(source);
return LocalDateTime.ofEpochSecond(milli, 0, ZoneOffset.UTC);
}
} public static class LocalDateConverter implements Converter<String, LocalDate> {
@Override
public LocalDate convert(String source) {
if (!NumberUtils.isDigits(source))
return null;
Long milli = NumberUtils.createLong(source);
return LocalDateTime.ofEpochSecond(milli, 0, ZoneOffset.UTC).toLocalDate();
}
}
SpringMvc Json LocalDateTime 互转,form urlencoded @ModelAttribute 转换的更多相关文章
- DataTable 和Json 字符串互转
#region DataTable 转换为Json字符串实例方法 /// <summary> /// GetClassTypeJosn 的摘要说明 /// </summary> ...
- C#中另辟蹊径解决JSON / XML互转的问题
C#中另辟蹊径解决JSON / XML互转的问题 最近在一个POC的项目中要用到JSON和XML的相互转换, 虽然我知道很多类库如JSON.NET具备这种功能, 但是我还是另辟蹊径的使用Spider ...
- Java8 LocalDateTime获取时间戳(毫秒/秒)、LocalDateTime与String互转、Date与LocalDateTime互转
本文目前提供:LocalDateTime获取时间戳(毫秒/秒).LocalDateTime与String互转.Date与LocalDateTime互转 文中都使用的时区都是东8区,也就是北京时间.这是 ...
- 二:C#对象、集合、DataTable与Json内容互转示例;
导航目录: Newtonsoft.Json 概述 一:Newtonsoft.Json 支持序列化与反序列化的.net 对象类型: 二:C#对象.集合.DataTable与Json内容互转示例: ...
- springMVC+json构建restful风格的服务
首先.要知道什么是rest服务,什么是rest服务呢? REST(英文:Representational State Transfer,简称REST)描写叙述了一个架构样式的网络系统.比方 web 应 ...
- struct2json -- C结构体与 JSON 快速互转库V1.0发布
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/zhutianlong/article/d ...
- Json对象与Json字符串互转(4种转换方式)
Json字符与Json对象的相互转换方式有很多,接下来将为大家一一介绍下,感兴趣的朋友可以参考下哈,希望可以帮助到你 1>jQuery插件支持的转换方式: 复制代码代码如下: $.parseJS ...
- Json对象与Json字符串互转(转载)
一.jQuery插件支持的转换方式 1 $.paseJSON(jsonstr);//将json字符串转换为json对象 二.浏览器支持的转换方式(Firefox,Chrome,Opera,Safair ...
- Json对象与Json字符串互转
1>jQuery插件支持的转换方式: 复制代码 代码如下: $.parseJSON( jsonstr ); //jQuery.parseJSON(jsonstr),可以将json字符串转换成js ...
随机推荐
- linkin大话设计模式--适配器模式
linkin大话设计模式--适配器模式 大家知道,在java中只允许单继承,但是在实际问题中往往都需要多继承,java引入了接口这一概念.(一个类可以实现多个接口) 由于接口中都是抽象方法,那么我们在 ...
- 新版elasticsearch的插件安装
安装 yum localinstall elasticsearch-6.1.1.rpm -y mkdir -p /elk/{data,logs} && chown -R elastic ...
- 【转】C++易混知识点5:实例讲解Public Protected Private作用域,继承的区别和用意
大学生涯,涉及到类的作用域,继承都是用的public 共有继承,当时也没想那么多,觉得共有继承多方便,多简单,反正没有太多的限制,不管是类的成员或者是基类的成员函数都可以访问.没有深究.其实这里面真是 ...
- 实现兼容document.querySelector的方法
var querySelector = function(selector) { //TODO 先简单兼容,后续继续扩展: var element = null; if(document.queryS ...
- Flex Grid学习-链接
这些是我个人在学习这两种布局的时候参考的资料,希望对大家有用-- 1.Flex 阮一峰(flex语法讲解):http://blog.csdn.net/naruto_luoluo/article/det ...
- BZOJ 2141: 排队 [CDQ分治]
题意: 交换序列中两个元素,求逆序对 做分块做到这道题...一看不是三维偏序嘛.... 作为不会树套树的蒟蒻就写CDQ分治吧.... 对时间分治...x排序...y树状数组... 交换拆成两个插入两个 ...
- POJ 3689 Apocalypse Someday [数位DP]
Apocalypse Someday Time Limit: 1000MS Memory Limit: 131072K Total Submissions: 1807 Accepted: 87 ...
- IntelliJ IDEA使用心得之插件篇
今天和大家分享下插件的安装方法,顺便推荐几个非常好用的插件. 1.安装插件 在工具栏中,点击进入IDE设置界面. 插件仓库界面: 值得注意的是,每次安装/卸载插件后,需要重启IDE. 2.好用的插件 ...
- Python数据结构之三——dict(字典)
Python版本:3.6.2 操作系统:Windows 作者:SmallWZQ 知识源于生活.Python也是如此. 提到字典,我首先想到的是数学大师--高斯. 为何想起他呢?这主要是因为高斯算法 ...
- 页面刷新方式实时检测cookie是否失效
在浏览器端每隔10秒钟刷新一次页面,可用于检查cookie值是否失效. 在study.php文件中存在这样一条语句: <meta http-equiv="refresh" c ...