第一步:创建CustomObjectMapper类
效果如下:
/**
* 解决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>效果如下:
格式化前:
格式化后:

本文介绍了如何通过创建CustomObjectMapper类并配合SpringMVC的<mvc:message-converters>配置,解决使用@ResponseBody返回json时日期格式默认显示为时间戳的问题,提供了一个实用的自定义日期格式化方案。
2769

被折叠的 条评论
为什么被折叠?



