第一種狀況是從後臺拿到數據,進行反序列化,反序列化格式時間:試了一下不少網上的方法,最後發現仍是在實體類上面的日期字段加上以下註解,能夠完成格式化操做,不然默認就都是時間戳的格式:html
@JSONField (format="yyyy-MM-dd HH:mm:ss") public Date birthday; @JSONField (format="yyyy-MM-dd HH:mm:ss") public Date birthday;
第二種狀況是:response返回給前段的時間格式,一開始是時間戳,須要轉成想要的格式yyyy-MM-dd重寫方法:java
package com.jjs.util; import java.io.IOException; import org.springframework.http.HttpOutputMessage; import org.springframework.http.converter.HttpMessageNotWritableException; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; public class JsonHttpMessageConverter extends FastJsonHttpMessageConverter { @Override protected void writeInternal(Object obj, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { // TODO Auto-generated method stub JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH"; JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat); super.writeInternal(obj, outputMessage); } }
而後,將springMVC.xml(具體文件名以項目而定) 的配置修改成以下, 引用重寫了writeInternal()方法的類進行json序列化spring
<mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <!-- <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> --> <bean class="com.jjs.util.JsonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>application/json</value> </list> </property> <property name="features"> <list> <value>WriteDateUseDateFormat</value> <value>WriteMapNullValue</value> <value>QuoteFieldNames</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>