【SpringMVC】【Retrofit】解決Http請求中的日期轉換問題

問題

Date對象在網絡通信中一般會被序列化爲三種形式:

  1. 13位時間戳
  2. 調用toString()函數產生的形如Sat Mar 02 17:12:05 GMT+08:00的帶時區信息的格式
  3. 自定義格式,如常見的年月日時分秒格式:yyyy-MM-dd HH:mm:ss 

對於從後端發送的數據,如果使用@ResponseBody註解返回json字符串,則Spring默認將Date對象序列化爲時間戳。

對於從前端發送的數據,因平臺不同而異。

爲統一起見,我們可固定將Date在網絡通信中序列化爲yyyy-MM-dd HH:mm:ss 格式。

解決

對於SpringMVC後端

在spring配置文件中加入(或修改):

<mvc:annotation-driven>
        <!-- 處理responseBody 裏面日期類型 -->
        <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>

即可全局設置格式轉換,

如果對於特定字段需要單獨處理,可在定義上加上@JsonFormat註解:

@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
Date date;

對於Andriod前端,使用Retrofit作爲網絡框架

定義Gson對象:

Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .serializeNulls()
                .create();

ConverterFactory中傳入Gson對象:

 retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(getOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create(gson)) //傳入gson對象
                .build();

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章