Spring mvc + jackson2 返回json格式(包含日期格式解析)

来源:互联网 发布:php sigusr2 编辑:程序博客网 时间:2024/06/03 19:50

写了那么多,发现白忙活了一场,原来jackson也有一个@JsonFormat注解,将它配置到Date类型的get方法上后,jackson就会按照配置的格式转换日期类型,而不自定义转换器类,欲哭无泪啊。辛苦了那么多,其实别人早已提供,只是没有发现而已。

不说了,直接上方案吧。

1.spring配置照样是这样:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <mvc:annotation-driven>  

2.JsonUtil可以不用了,但如果要自己从response对象输出json,那么还是可以用,但改成了这样

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. package com.xxx.utils;  
  2.   
  3. import java.io.IOException;  
  4. import java.text.SimpleDateFormat;  
  5. import org.springframework.stereotype.Component;  
  6. import com.fasterxml.jackson.databind.ObjectMapper;  
  7.   
  8. /** 
  9.  * json处理工具类 
  10.  * @author zhangle 
  11.  */  
  12. @Component  
  13. public class JsonUtil {  
  14.   
  15.     private static final String DEFAULT_DATE_FORMAT="yyyy-MM-dd HH:mm:ss";  
  16.     private static final ObjectMapper mapper;  
  17.   
  18.     static {  
  19.         SimpleDateFormat dateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);  
  20.         mapper = new ObjectMapper();  
  21.         mapper.setDateFormat(dateFormat);  
  22.     }  
  23.       
  24.     public static String toJson(Object obj) {  
  25.         try {  
  26.             return mapper.writeValueAsString(obj);  
  27.         } catch (Exception e) {  
  28.             throw new RuntimeException("转换json字符失败!");  
  29.         }  
  30.     }  
  31.       
  32.     public <t> T toObject(String json,Class<t> clazz) {  
  33.         try {  
  34.             return mapper.readValue(json, clazz);  
  35.         } catch (IOException e) {  
  36.             throw new RuntimeException("将json字符转换为对象时失败!");  
  37.         }  
  38.     }  
  39. }</t></t>  

3.实体类的get方法就需要多一个@JsonFormat的注解配置

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")  
  2. @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")  
  3. public Date getCreateTime() {  
  4. return this.createTime;  
  5. }  
  6. @DateTimeFormat(pattern="yyyy-MM-dd")  
  7. @JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")  
  8. public Date getBirthday() {  
  9.     return this.birthday;  
  10. }  
0 0
原创粉丝点击