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 ...
随机推荐
- BSA Network Shell系列-nsh命令
nsh nsh命令软链接到zsh,直接运行nsh可进入Network Shell,所有的Network Shell命令都需要运行nsh进入Network Shell执行 1 使用cd命令访问远程主机和 ...
- PowerCLI: One-Liner to get VMs, Clusters, ESX Hosts and Datastores并导入数据库中
需求:定期自动获取Vm在VCenter中对应的cluster.ESX.Datastore信息,同时将变化或者新增的数据上传到数据库中 解决思路分析: 1 首先使用VMware的powerCLI工具通过 ...
- Tomcat 的设计模式分析
最近在研究tomcat,手上有一份尚硅谷的tomcat设计模式的资料,翻开看了看个人觉得写得还是很好的.设计模式一般都是在有一定的代理积累之后才能用到的相关的这种解决方案.常用的一共有23种设计模式, ...
- js给页面添加滚动事件并判断滚动方向
<script> var scrollFunc = function (e) { var direct = 0; e = e || window.event; if (e.wheelDel ...
- 达尔稳usb转RJ45的接口转换器(usb2.0接口)在ubuntu16.04中驱动(r8152)编译安装与使用
淘宝买了usb转RJ45的接口转换器:https://detail.tmall.com/item.htm?id=524808012954&ali_refid=a3_430582_1006:11 ...
- FBReader阅读引擎支持的功能
"三十年河东,三十年河西"是一句民间谚语,它的来源是:从前黄河河道不固定,经常会改道(历史上无数次发生).某个地方原来在河的东面,若干年后,因黄河水流改道,这个地方会变为在河的西面 ...
- Call to undefined function mysql_connect()错误原因
从PHP5.0开始就不推荐使用mysql_connect()函数,到了php7.0则直接废弃了该函数,替代的函数是: mysqli_connect();
- 网易云免费OSS服务用做Markdown图床或博客图片外链
我使用据说是Windows下最好用的Markdown编辑器“MarkdownPad2”(个人感觉还是Visual Code+Markdown插件666)写Markdown,在贴图方面遇到一个问题,于是 ...
- Jmeter Smock Test规范设计
Jmeter Smock Test规范设计 一.Smock Test物料 1.开发运行工具Jmeter,(下载地址: http://jmeter.apache.org/download_jmeter. ...
- POJ 3590 The shuffle Problem [置换群 DP]
传送门 $1A$太爽了 从此$Candy?$完全理解了这种$DP$做法 和bzoj1025类似,不过是求最大的公倍数,并输出一个字典序最小的方案 依旧枚举质因子和次数,不足的划分成1 输出方案从循环长 ...