日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SpringMVC在使用Jackson2时关于日期类型格式化的问题

發布時間:2023/12/18 javascript 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringMVC在使用Jackson2时关于日期类型格式化的问题 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

*本例程序使用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。

轉載于:https://www.cnblogs.com/lichmama/p/7867273.html

總結

以上是生活随笔為你收集整理的SpringMVC在使用Jackson2时关于日期类型格式化的问题的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。