Spring MVC JSON自定义类型转换

来源:互联网 发布:java面试题及答案2016 编辑:程序博客网 时间:2024/05/23 01:01

类型有很多,这里只用日期为例说明。


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


JSON:

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

[java] view plaincopyprint?在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.     } 

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

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

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


两个具体转换类的实现:

[java] view plaincopyprint?在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 DateYMDHMSJsonSerializerextends 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.     } 

[java] view plaincopyprint?在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 DateYMDHMSJsonDeserializerextends 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.     } 

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


Binder:

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

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. /**
  2. * Description: 全局类型转换
  3. * Author: liuzh
  4. * Update: liuzh(2014-05-26 13:08)
  5. */ 
  6. public class GlobalDataBinderimplements 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 SmartDateEditorextends 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.                         thrownew 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.                     } elseif (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.  

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

[html] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 
  2.     <propertyname="webBindingInitializer"> 
  3.       <beanclass="com.easternie.sys.common.GlobalDataBinder"/> 
  4.     </property> 
  5. </bean> 
通过这种配置之后,Spring就能对日期进行智能转换了。
0 0
原创粉丝点击