*本例程序使用Jackson2.9.0,jackson1.x的處理方式稍稍有些不同。
在基於Spring&SpringMVC的Web項目中,我們常使用Jackson(1.x/2.x)來增加程序對Json格式的數據的支持。
因此,在實際應用中有個常見的需求:日期的格式化。
假設,User對象有個Date類型的屬性birthday:
class User implements Serializable { private Date birthday; //... }
程序支持如下api請求,而我們希望在返回Json格式的User資料時,對Date類型的birthday進行一下格式化。
@Controller class UserAction { @RequestMapping("/user/find/{id}") public @ResponseBody User getUserById(@PathVariable("id") int id) { return userService.getUserById(id); } }
實現上述需求大體有兩種常用的方式:
1.使用@JsonFormat注解
該方法只需在關鍵字段加上@JsonFormat注解即可,如下:
class User implements Serializable { @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date birthday; //... }
參數解釋:pattern - 格式,timezone - 時區
2.設置MappingJackson2HttpMessageConverter的objectMapper
該方法主要對json數據轉換時用到的HttpMessageConverter進行一些設置,進一步講就是objectMapper在對日期類型數據序列化時設置成統一的pattern,配置如下:
<mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="com.fasterxml.jackson.databind.ObjectMapper"> <property name="dateFormat"> <bean class="java.text.SimpleDateFormat"> <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" /> </bean> </property> </bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
或者:
<bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"> <property name="simpleDateFormat" value="yyyy-MM-dd HH:mm:ss" /> </bean> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper" ref="objectMapper" /> </bean> </mvc:message-converters> </mvc:annotation-driven>
方法1使用起來方便靈活,但如果有大量需要統一設置的字段屬性,那么推薦使用方法2。或者兩種方法混合使用,作用優先級:方法1 > 方法2。