【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();

猜你喜欢

转载自blog.csdn.net/qq_39821316/article/details/88078658