【SpringMVC】【Retrofit】解决Http请求中的日期转换问题

本文探讨了在网络通信中Date对象的序列化问题,通常有时间戳、带时区的toString格式和自定义格式。针对SpringMVC后端,可以通过配置全局日期格式或使用@JsonFormat注解对特定字段进行格式化。而在Android前端,当使用Retrofit作为网络框架时,可以定制Gson对象来实现日期格式的一致性,确保在网络通信中Date始终以'yyyy-MM-dd HH:mm:ss'格式传递。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值