Spring MVC JSON 实现JsonSerializer Date类型转换

转载至:http://blog.csdn.net/lantianzhange/article/details/40920933

在Spring MVC中存在两大类的类型转换,一类是Json,一个是Spring的Binder转换。

JSON:

使用Json转换时,可以如下使用:

  1. public class Test {    
  2.            
  3.        private Date createdate;    
  4.        
  5.        @JsonSerialize(using = DateYMDHMSJsonSerializer.class)    
  6.        public Date getCreatedate() {    
  7.            return createdate;    
  8.        }    
  9.        
  10.        @JsonDeserialize(using = DateYMDHMSJsonDeserializer.class)    
  11.        public void setCreatedate(Date createdate) {    
  12.            this.createdate = createdate;    
  13.        }    
  14.    }    



可以看到这里使用了两个Json转换的注解:

第一个@JsonSerialize是转换为字符串,主要是后台传递给前台时的日期格式;

第二个@JsonDeserialize是转换字符串为日期类型,主要是从前台往后台传递时的日期。

两个具体转换类的实现:

  1. /**   
  2.  * Description: 日期转换 - "yyyy-MM-dd HH:mm:ss"   
  3.  * Author: liuzh   
  4.  * Update: liuzh(2014-04-17 10:59)   
  5.  */    
  6. public class DateYMDHMSJsonSerializer extends JsonSerializer<Date>{    
  7.     @Override    
  8.     public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {    
  9.         try {    
  10.             jsonGenerator.writeString(DateUtil.formatDate(date, DateUtil.DATE_FORMAT_TIME_T));    
  11.         } catch (BusinessException e) {    
  12.             jsonGenerator.writeString(String.valueOf(date.getTime()));    
  13.         }    
  14.     }    
  15. }    
  1. /**   
  2.  * Description: 日期转换 - "yyyy-MM-dd HH:mm:ss"   
  3.  * Author: liuzh   
  4.  * Update: liuzh(2014-04-17 10:59)   
  5.  */    
  6. public class DateYMDHMSJsonDeserializer extends JsonDeserializer<Date> {    
  7.     @Override    
  8.     public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {    
  9.         try {    
  10.             return DateUtil.formatStringToDate(jp.getText(), DateUtil.DATE_FORMAT_TIME_T);    
  11.         } catch (BusinessException e) {    
  12.             return new Date(jp.getLongValue());    
  13.         }    
  14.     }    
  15. }    


其中DateUtil是一个对日期格式转换的工具类,使用的SimpleDateFormat进行转换。

Binder:

这种类型转换的时候,使用的是Spring的参数绑定,代码如下:

  1. /**   
  2.  * Description: 全局类型转换   
  3.  * Author: liuzh   
  4.  * Update: liuzh(2014-05-26 13:08)   
  5.  */    
  6. public class GlobalDataBinder implements WebBindingInitializer {    
  7.     /**   
  8.      * 智能日期转换,针对四种格式日期:   
  9.      * 1.2014-05-26   
  10.      * 2.1401951570548   
  11.      * 3.2014-05-26 00:00   
  12.      * 4.2014-05-26 00:00:00   
  13.      */    
  14.     private class SmartDateEditor extends PropertyEditorSupport {    
  15.         /**   
  16.          * 根据2014-05-26 00:00:00长度来判断选择哪种转换方式   
  17.          */    
  18.         @Override    
  19.         public void setAsText(String text) throws IllegalArgumentException {    
  20.             if (text == null || text.length() == 0) {    
  21.                 setValue(null);    
  22.             } else {    
  23.                 try {    
  24.                     if (text.length() == 10) {    
  25.                         setValue(DateUtil.formatStringToDate(text, DateUtil.DATE_FORMAT_YYYYMMDD));    
  26.                     } else if (text.length() == 13) {    
  27.                         setValue(new Date(Long.parseLong(text)));    
  28.                     } else if (text.length() == 16) {    
  29.                         setValue(DateUtil.formatStringToDate(text, DateUtil.DATE_FORMAT_TIME_R));    
  30.                     } else if (text.length() == 19) {    
  31.                         setValue(DateUtil.formatStringToDate(text, DateUtil.DATE_FORMAT_TIME_T));    
  32.                     } else {    
  33.                         throw new IllegalArgumentException("转换日期失败: 日期长度不符合要求!");    
  34.                     }    
  35.                 } catch (Exception ex) {    
  36.                     throw new IllegalArgumentException("转换日期失败: " + ex.getMessage(), ex);    
  37.                 }    
  38.             }    
  39.         }    
  40.     
  41.         /**   
  42.          * 转换为日期字符串   
  43.          */    
  44.         @Override    
  45.         public String getAsText() {    
  46.             Date value = (Date) getValue();    
  47.             String dateStr = null;    
  48.             if (value == null) {    
  49.                 return "";    
  50.             } else {    
  51.                 try {    
  52.                     dateStr = DateUtil.formatDate(value, DateUtil.DATE_FORMAT_TIME_T);    
  53.                     if (dateStr.endsWith(" 00:00:00")) {    
  54.                         dateStr = dateStr.substring(0, 10);    
  55.                     } else if (dateStr.endsWith(":00")) {    
  56.                         dateStr = dateStr.substring(0, 16);    
  57.                     }    
  58.                     return dateStr;    
  59.                 } catch (Exception ex) {    
  60.                     throw new IllegalArgumentException("转换日期失败: " + ex.getMessage(), ex);    
  61.                 }    
  62.             }    
  63.         }    
  64.     }    
  65.     
  66.     @Override    
  67.     public void initBinder(WebDataBinder binder, WebRequest request) {    
  68.         //日期格式转换    
  69.         binder.registerCustomEditor(Date.class, new SmartDateEditor());    
  70.     }    
  71.     
  72. }    


这里对日期类型进行了一些判断来特殊处理。该类需要在Spring的xml进行配置:

  1. <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">    
  2.     <property name="webBindingInitializer">    
  3.       <bean class="com.easternie.sys.common.GlobalDataBinder"/>    
  4.     </property>    
  5. </bean>    


通过这种配置之后,Spring就能对日期进行自由转换了。

原文地址:https://www.cnblogs.com/caroline/p/4308007.html