Spring3.1返回Json时格式化日期Date

来源:互联网 发布:淘宝网宝贝卖点怎么写 编辑:程序博客网 时间:2024/06/05 08:00

Spring3.1返回Json时格式化日期Date

分类: Java Spring 1189人阅读 评论(0)收藏 举报
第一步:创建CustomObjectMapper类
[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /**  
  2.  * 解决SpringMVC使用@ResponseBody返回json时,日期格式默认显示为时间戳的问题。需配合<mvc:message-converters>使用  
  3.  *   
  4.  * @author hellostory  
  5.  * @date 2013-10-31 下午04:17:52  
  6.  */  
  7. @Component("customObjectMapper")  
  8. public class CustomObjectMapper extends ObjectMapper {  
  9.   
  10.     public CustomObjectMapper() {  
  11.         CustomSerializerFactory factory = new CustomSerializerFactory();  
  12.         factory.addGenericMapping(Date.class, new JsonSerializer<Date>() {  
  13.             @Override  
  14.             public void serialize(Date value, JsonGenerator jsonGenerator,  
  15.                     SerializerProvider provider) throws IOException, JsonProcessingException {  
  16.                 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  17.                 jsonGenerator.writeString(sdf.format(value));  
  18.             }  
  19.         });  
  20.         this.setSerializerFactory(factory);  
  21.     }  
  22. }  


第二步:配置如下:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <mvc:annotation-driven>  
  2.     <mvc:message-converters>  
  3.         <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">  
  4.             <property name="objectMapper" ref="customObjectMapper"></property>  
  5.         </bean>  
  6.     </mvc:message-converters>  
  7. </mvc:annotation-driven>  

效果如下:

格式化前:


格式化后:

0 0
原创粉丝点击