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 ...
随机推荐
- Linux指令--head,tail
原文出处:http://www.cnblogs.com/peida/archive/2012/11/06/2756278.html head 与 tail 就像它的名字一样的浅显易懂,它是用来显示开头 ...
- java获取昨天的日期
Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -1); String yesterday = new ...
- 【转】C++易混知识点1: 指针常量和常量指针的区别,附有详细案例解释
熟悉C++也已经有一些年头了,今天突然翻出当年浏览的书籍,对一些概念居然生疏了,指针常量和常量指针由于 指针 这一特殊的对象而变得难以区别.因此,在思考再三之后,决定写下该篇总结,加强对他们的区别: ...
- Docker最佳实践-部署LNMP环境
标签(linux): docker 笔者Q:972581034 交流群:605799367.有任何疑问可与笔者或加群交流 环境准备 [root@docker ~]# cat /etc/redhat-r ...
- notepad++代码输出电话号
在网上看到一个程序员找合租的消息,希望找一个程序员合租,所以电话号码以代码的形式输出,闲来没事打出来玩玩.首先新建一个test.java文件,并敲入下面代码: 1 public class test{ ...
- 创建github仓库的gh-pages分支
用git symbolic-ref命令将当前工作分支由master切换到一个尚不存在的分支gh-pages. $ git symbolic-ref HEAD refs/heads/gh-pages 删 ...
- iOS-strong和copy【详细解读】
strong和copy是常用到的修饰符,那么什么时候用strong,什么时候用copy,先上一段代码再说(以下代码直接在ViewController中写): 先定义两个数组 ///strong @pr ...
- java签名与验签
基本概念: 加密解密 加密:发送方利用接收方的公钥对要发送的明文进行加密. 解密:接收方利用自己的私钥进行解密. 公钥和私钥配对的,用公钥加密的文件,只有对应的私钥才能解密.当然也可以反过来,用私钥加 ...
- StringBuffer和String需要注意的
首先,StringBuffer的toString方法和String的subString方法都是在新生成了一个新的String. 最近做的一个功能,多线程的从SQLite数据库中读取数据.将数据拼成在M ...
- 洛谷 [P1154] 奶牛分厩
类似筛法的思想 本题实际上就是反推hash的模数, 首先想到枚举k,但显然会超时. $a mod k==b mod k <==> k|(a-b) $ 由同余的定义可以知道 所以我们的任务就 ...