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 ...
随机推荐
- C# MongoDB
一.搭建Mongodb 副本集 副本集中有三个角色: 主节点:所有副节点的数据均来自于主节点,并且只能对主节点进行读写操作.副节点:数据来自于主节点,可以进行读取操作,但是不能进行写操作.仲裁者:不含 ...
- 安卓和IOS兼容问题
点击穿透 click延迟 scroll元素临界的bug android screen.w/h 不准 rem不准 scroll时动画失效 animate回调 最小字号限制 不同机型全屏自适应 andro ...
- mybatis-spring最新版下载地址
mybatis-spring最新版下载地址: http://mvnrepository.com/artifact/org.mybatis/mybatis-spring/1.2.3 mybatis-sp ...
- python --- 基础多线程编程
在python中进行多线程编程之前必须了解的问题: 1. 什么是线程? 答:线程是程序中一个单一的顺序控制流程.进程内一个相对独立的.可调度的执行单元,是系统独立调度和分派CPU的基本单位指运行中的程 ...
- Codeforce D. Make a Permutation!
D. Make a Permutation! time limit per test 2 seconds memory limit per test 256 megabytes input stand ...
- oracle pl/sql中的循环及if语句
for循环 /* for循环打印1到10 */ set serveroutput on; declare begin .. loop dbms_output.put_line(i); end loop ...
- pwd 的“P”选项
1.目录是链接目录时,pwd -P 显示出实际路径,而非使用连接(link)路径:pwd显示的是连接路径 例: [root@localhost soft]# cd /etc/init.d [root ...
- dump、libeay32.dll、gsoap、webserver多线程调用gsoap产生崩溃
问题:调用webserver接口出现dump文件,dump文件指向libeay32.dll有问题,产生崩溃的原因是gsoap多线程问题,多线程调用时需要程序启动的地方调用如下函数进行多线程初始化: i ...
- 精通libGDX-RPG开发实战
从今天开始,我会陆陆续续做一个五脏俱全的rpg小品游戏. 素材使用<圣剑英雄传II>的素材 游戏名称< Inspiration > 教程目录(暂定): Chapter 1: 开 ...
- BZOJ 2073: [POI2004]PRZ [DP 状压]
传送门 水题不解释 这道题的主要目的在于记录一个枚举子集的技巧 #include <iostream> #include <cstdio> #include <cstri ...