您的位置:首页 > 编程语言 > Java开发

格式化Spring MVC 返回json的Date格式

2015-01-13 10:41 323 查看
在Spring MVC中,返回JSON,需通过org.springframework.http.converter.json.MappingJacksonHttpMessageConverter对对象进行转换。

MappingJacksonHttpMessageConverter对Date的json输出为一个数字.

方法一、为了格式化Date的JSON输出样式,需要新建ObjectMapper,MappingJacksonHttpMessageConverter使用。

具体代码如下所示:(代码转自:http://blog.csdn.net/hellostory/article/details/17916413)

/**
* 解决SpringMVC使用@ResponseBody返回json时,日期格式默认显示为时间戳的问题。需配合<mvc:message-converters>使用
*
* @author hellostory
* @date 2013-10-31 下午04:17:52
*/
@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 value, JsonGenerator jsonGenerator,
SerializerProvider provider) throws IOException, JsonProcessingException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
jsonGenerator.writeString(sdf.format(value));
}
});
this.setSerializerFactory(factory);
}
}


<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper" ref="customObjectMapper"></property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>


方法二、定义一个类MyBinder实现WebBindingInitializer接口实现其方法public void initBinder(WebDataBinder binder, WebRequest arg1) {},接着在spring-mvc.xml中配置

<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>  <!-- 这个类里面你可以注册拦截器什么的 -->
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean class="packagename.MyBinder"></bean>  <!-- 这里注册自定义数据绑定类 -->
</property>
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter"/>    <!-- 注册JSON  Converter-->
</list>
</property>
</bean>
此jacksonMessageConverter是必须配置的,否则无法返回Json

此webBindingInitializer是对所有Controller的对象转换生效的,不仅是json
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: