解决Spring中@ResponseBody 返回json字符串date类型变成long型的问题_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 解决Spring中@ResponseBody 返回json字符串date类型变成long型的问题

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

 2014/11/14 16:03:33  jynine  程序员俱乐部  我要评论(0)
  • 摘要:packagecom.jynine.service;importjava.io.IOException;importjava.text.SimpleDateFormat;importjava.util.Date;importorg.codehaus.jackson.JsonGenerator;importorg.codehaus.jackson.JsonProcessingException;importorg.codehaus.jackson.map.JsonSerializer
  • 标签:解决 问题 Spring 字符串 JSON JS
class="java" name="code">
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>

上一篇: 配置JNDI 下一篇: 食之无味弃之可惜的RSS
发表评论
用户名: 匿名