1. 程式人生 > >SpringMVC返回json資料的日期格式統一轉換

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
        }
    }
}