`

解决Spring中@ResponseBody 返回json字符串date类型变成long型的问题

阅读更多
package com.jynine.service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.ser.CustomSerializerFactory;
import org.springframework.stereotype.Component;
/**
 * 
 * <p>Title: CustomObjectMapper.java</p>
 * <p>Description:解决SpringMVC使用@ResponseBody返回json时,日期格式默认显示为时间戳的问题 </p>
 * @author jynine
 * @date 2014-11-14
 */
@Component("customObjectMapper")
public class CustomObjectMapper extends ObjectMapper{

	public CustomObjectMapper() {
		CustomSerializerFactory factory = new CustomSerializerFactory();
		factory.addGenericMapping(Date.class, new JsonSerializer<Date>() {

			@Override
			public void serialize(Date arg0, JsonGenerator arg1,
					SerializerProvider arg2) throws IOException,
					JsonProcessingException {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				arg1.writeString(sdf.format(arg0));
			}
			
		});
		this.setSerializerFactory(factory);
	}
}


servlet-context.xml中添加

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="jsonConverter"/>
			</list>
		</property>
	</bean>

	<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
		<property name="supportedMediaTypes" value="application/json" />
		<property name="objectMapper" ref="customObjectMapper"></property>
	</bean>

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics