BUG战斗史 —— 日期格式与字符串之间的转换

说在前面

最近在公司实习,接触了一个中小型的后台管理系统,不得不说,项目的目录结构比我平时做的"课程设计"要来得复杂,于是我先去看了Github上一些后台管理系统的模板项目

在guns(https://gitee.com/stylefeng/guns)后台管理系统中,我用"代码生成"功能生成模板页面和后台代码后,将一个含有日期类型的实体类的记录添加到数据表,中间总是碰到一个类型转换的错误

我的第一反应就是自定义一个继承JsonDeserialize<Date>抽象类的具体类,然后在日期类型字段上添加@JsonDeserialize(using = ***.class)注解,但是一直不成功

public class StringToDateConvert extends JsonDeserializer<Date> {
  private final String[] patterns = {
    "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss",
    "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss"
  };
  @Override
  public Date deserialize(JsonParser p, DeserializationContext ctxt)
  throws IOException, JsonProcessingException {
    String str = p.getText();
    if (StringUtils.isEmpty(str)) {
      return null;
    } else {
      try {
        return DateUtils.parseDate(str, Locale.CHINA, patterns);
      } catch (ParseException e) {
        e.printStackTrace();
        return null;
      }
    }
  }
}
//
添加注解到对应字段
@JsonDeserialize(using = StringToDateConvert.class)
private Date dateField;

经过debug调试,发现根本就没有经过我的自定义反序列化类

 

打倒BUG

之前有很长一段时间我做的都是前后端分离的项目,大多数情况下都通过Json格式传递数据,Http请求头的Content-Type为 application/json类型

但是在guns中,Http请求头的Content-Type为application/x-www-form-urlencoded类型,所以我自定义的Json反序列化配置自然就不会起作用,常见的三种Content-Type如下:

application/json

数据以Json格式发送

application/x-www-form-urlencoded

form标签中默认的encType,数据被编码为键值对格式,各键值对以&分隔后发送

multipart/form-data

常用于文件上传

最后,我通过在字段上添加@DateTimeFormat(pattern = "yyyy-MM-dd")注解解决了这个问题,这是一个非常便捷的注解,可以作用在多种表示时间的类上

Declares that a field or method parameter should be formatted as a date or time. Supports formatting by style pattern, ISO date time pattern, or custom format pattern string. Can be applied to java.util.Date, java.util.Calendar, java.lang.Long, Joda-Time value types; and as of Spring 4 and JDK 8, to JSR-310 java.time types too.

posted @ 2020-07-26 15:03  咕~咕咕  阅读(293)  评论(0编辑  收藏  举报