Spring MVC JSON 實現JsonSerializer Date類型轉換

轉載至:http://blog.csdn.net/lantianzhange/article/details/40920933html

在Spring MVC中存在兩大類的類型轉換,一類是Json,一個是Spring的Binder轉換。java

JSON:web

使用Json轉換時,能夠以下使用:spring

 

[java]  view plain copy print ? 在CODE上查看代碼片 派生到個人代碼片
 
  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轉換的註解:json

 

第一個@JsonSerialize是轉換爲字符串,主要是後臺傳遞給前臺時的日期格式;mvc

第二個@JsonDeserialize是轉換字符串爲日期類型,主要是從前臺日後臺傳遞時的日期。ide

 

兩個具體轉換類的實現:工具

[html]  view plain copy print ? 在CODE上查看代碼片 派生到個人代碼片
 
  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. }    

 

[html]  view plain copy print ? 在CODE上查看代碼片 派生到個人代碼片
 
  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進行轉換。this

 

Binder:spa

這種類型轉換的時候,使用的是Spring的參數綁定,代碼以下:

[html]  view plain copy print ? 在CODE上查看代碼片 派生到個人代碼片
 
  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進行配置:

 

[html]  view plain copy print ? 在CODE上查看代碼片 派生到個人代碼片
 
  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就能對日期進行自由轉換了。

相關文章
相關標籤/搜索