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 转换的更多相关文章

  1. DataTable 和Json 字符串互转

    #region DataTable 转换为Json字符串实例方法 /// <summary> /// GetClassTypeJosn 的摘要说明 /// </summary> ...

  2. C#中另辟蹊径解决JSON / XML互转的问题

    C#中另辟蹊径解决JSON / XML互转的问题 最近在一个POC的项目中要用到JSON和XML的相互转换, 虽然我知道很多类库如JSON.NET具备这种功能, 但是我还是另辟蹊径的使用Spider ...

  3. Java8 LocalDateTime获取时间戳(毫秒/秒)、LocalDateTime与String互转、Date与LocalDateTime互转

    本文目前提供:LocalDateTime获取时间戳(毫秒/秒).LocalDateTime与String互转.Date与LocalDateTime互转 文中都使用的时区都是东8区,也就是北京时间.这是 ...

  4. 二:C#对象、集合、DataTable与Json内容互转示例;

    导航目录: Newtonsoft.Json 概述 一:Newtonsoft.Json 支持序列化与反序列化的.net 对象类型:    二:C#对象.集合.DataTable与Json内容互转示例: ...

  5. springMVC+json构建restful风格的服务

    首先.要知道什么是rest服务,什么是rest服务呢? REST(英文:Representational State Transfer,简称REST)描写叙述了一个架构样式的网络系统.比方 web 应 ...

  6. struct2json -- C结构体与 JSON 快速互转库V1.0发布

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/zhutianlong/article/d ...

  7. Json对象与Json字符串互转(4种转换方式)

    Json字符与Json对象的相互转换方式有很多,接下来将为大家一一介绍下,感兴趣的朋友可以参考下哈,希望可以帮助到你 1>jQuery插件支持的转换方式: 复制代码代码如下: $.parseJS ...

  8. Json对象与Json字符串互转(转载)

    一.jQuery插件支持的转换方式 1 $.paseJSON(jsonstr);//将json字符串转换为json对象 二.浏览器支持的转换方式(Firefox,Chrome,Opera,Safair ...

  9. Json对象与Json字符串互转

    1>jQuery插件支持的转换方式: 复制代码 代码如下: $.parseJSON( jsonstr ); //jQuery.parseJSON(jsonstr),可以将json字符串转换成js ...

随机推荐

  1. 使用EndNote在Word中插入参考文献的格式设置

    endnote其实自带了很多参考文献格式的样式,如下图,但往往跟我们要使用的会有所出入,本文主要介绍的就是设置自定义endnote参考文献格式,以endnote X6和word2003为例,其它版本以 ...

  2. SQL SERVER的单用户模式以及专用管理员连接

    2007-03-08 18:22:03.46 server    Microsoft SQL Server  2000 - 8.00.2039 (Intel X86) May  3 2005 23:1 ...

  3. android .9图片的制作

    android .9PNG图片制作 在android开发的过程中,我们经常因为没有好的美工图片失真,这样使界面看起来要逊色很多,有的时候可能我们会想在drawable-hdpi,ldpi,mdpi下放 ...

  4. Ajax 基础笔记

    Ajax内容: 同步交互与异步交互 同步交互:客户端向服务器端发送请求,服务器端向客户端进行响应,这个过程中客户端不能做其他事情 异步交互:客户端向服务器端发送请求,服务器端向客户端进行响应,这个过程 ...

  5. 【转】sed正则表达式

    1 正则表达式简介 正则表达式(Regular Expression) 是一种描述文本(或字符串)模式的工具.正则表达式常用于查找文本的场合.想想一下我们日常生活中的例子,假如你想从电话本里找一个联系 ...

  6. iOS 设置文本中指定某段文本的颜色 大小

    NSString *money = @"300"; NSString *perStr = @"元/时"; NSString *text = [NSString  ...

  7. HTTP就是这么简单

    为什么要学HTTP? 我们绝大多数的Web应用都是基于HTTP来进行开发的.我们对Web的操作都是通过HTTP协议来进行传输数据的. 简单来说,HTTP协议就是客户端和服务器交互的一种通迅的格式. H ...

  8. Spring MVC的优势

    Spring 框架提供了构建Web应用程序的全功能MVC模块--Spring MVC. Spring MVC框架提供了一个DispatcherServlet作为前端控制器来分派请求,同时提供灵活的配置 ...

  9. JavaScript基本语法 -- 条件语句 & 循环语句

    条件语句 条件语句(Conditional statement)是JavaScript里面的基本结构之一,程序根据表达式的真假决定执行或者跳过某个分支,于是,条件语句有时候也可以称为"分支语 ...

  10. javase学习小结三

    格式标识符: System.out.printf("%d,%f,%5d,%-9.4f,%%,%13e",67,78.9,89,78.9,567.345); 输出结果为:67,78. ...