SpringMVC返回json数据的日期格式统一转换 - Go语言中文社区

SpringMVC返回json数据的日期格式统一转换


有时候我们做接口时候,返回json的数据,controller层的方法用@ResponseBody注解,方法返回的是一个bean,bean里面可能有个从数据库获取的数据map,如果有日期格式的字段,可能返回的是时间戳的日期。



解决方法有两种

1.增加map xml的数据类型处理.实现TypeHandler接口,重写getResult方法。(每个字段都写很繁琐)

<resultMap type="map" id="mbrMap">
	<result column="AUTH_TIME" property="CREATE_TIM" typeHandler="com.neil.common.handler.TimeValueHandler"/>		
</resultMap>

<select id="queryMem" parameterType="map" resultMap="mbrMap">
	select * from table		
</select>

package com.neil.common.handler;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

public class TimeValueHandler implements TypeHandler<String>{

	private SimpleDateFormat  sd = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
	
	@Override
	public String getResult(ResultSet rs, String str) throws SQLException {
		return sd.format(rs.getTimestamp(str));
	}

	@Override
	public String getResult(ResultSet arg0, int arg1) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getResult(CallableStatement arg0, int arg1) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setParameter(PreparedStatement arg0, int arg1, String arg2, JdbcType arg3) throws SQLException {
		// TODO Auto-generated method stub
		
	}



	
	
	
	
}


2.Spring MVC的自动转换功能 HttpMessageConverter。指定返回json的日期格式。(推荐,统一处理)

<!-- 启用spring mvc 注解-->
<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>  

效果

{
    "resultCode": "00000",
    "resultMsg": "SUCCESS",
    "bodyMap": {
        "result": {
            "AUTH_TIME": "2016-05-10 17:58:55",
            "ID": 23006
        }
    }
}



版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/nk_tf/article/details/53644626
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-07 22:28:44
  • 阅读 ( 396 )
  • 分类:前端

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢