以前,关于返回json字符串date类型变成long(时间戳)类型,一直存在困难,两个方面,1,通过前端的格式转化;2,同事date转成string类型,再做传值,如此既降低编码效率又不利于全端开发人员的工作负担。为此今天做如下总结;
第一步:设计组价
package edu.sjtu.nicman.web.controller.config;
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;
@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);
}
}
第二步:组件配置
以下是对json格式和date类型时间转化的配置
<!-- 以下为SpringMVC配置 -->
<mvc:annotation-driven>
<!-- 返回json数据,@response使用 -->
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper" ref="customObjectMapper"></property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
第三步:在需要转换格式的字段添加注解
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date time0;