一、spring boot默認使用jackson對json序列化和發序列化java
可在配置文件中增長默認的時間格式化方式:spring
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8json
import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; public class MrType { @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd") @DateTimeFormat(pattern="yyyy-MM-dd") private Date createdDate; }
二、使用fastjson對json數據序列化和發序列化測試
import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.http.converter.HttpMessageConverter; @SpringBootApplication public class MonitorRedbagMqApplication { public static void main(String[] args) { SpringApplication.run(MonitorRedbagMqApplication.class, args); } @Bean public HttpMessageConverters fastJsonHttpMessageConverters() { //FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); //FastJsonConfig fastJsonConfig = new FastJsonConfig(); //fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); //fastConverter.setFastJsonConfig(fastJsonConfig); //HttpMessageConverter<?> converter = fastConverter; //return new HttpMessageConverters(converter); //建立fastJson消息轉換器 FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter(); //建立配置類 FastJsonConfig fastJsonConfig = new FastJsonConfig(); //過濾並修改配置返回內容 fastJsonConfig.setSerializerFeatures( //List字段若是爲null,輸出爲[],而非null SerializerFeature.WriteNullListAsEmpty, //字符類型字段若是爲null,輸出爲"",而非null SerializerFeature.WriteNullStringAsEmpty, //Boolean字段若是爲null,輸出爲false,而非null //SerializerFeature.WriteNullBooleanAsFalse, //消除對同一對象循環引用的問題,默認爲false(若是不配置有可能會進入死循環) SerializerFeature.DisableCircularReferenceDetect, //是否輸出值爲null的字段,默認爲false。 SerializerFeature.WriteMapNullValue ); //處理中文亂碼問題 List<MediaType> fastMediaTypes = new ArrayList<>(); fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); fastJsonConverter.setSupportedMediaTypes(fastMediaTypes); fastJsonConverter.setFastJsonConfig(fastJsonConfig); HttpMessageConverter<?> converter = fastJsonConverter; return new HttpMessageConverters(converter); } }
三、測試Java對象code
public class MonitorRedbagDto implements Serializable { private static final long serialVersionUID = -1600920246142453543L; // 紅包ID private Integer redbagId; // 用戶ID private Long userId; // 發放時間 @JSONField(format = "yyyy-MM-dd HH:mm:ss") private Date sendTime; // setter getter方法 }
若是不用fastjson序列化,返回:orm
{ "redbagId": null, "userId": 16, "sendTime": "2018-03-06T12:04:15.483+0000" }
使用fastjson序列化,返回:xml
{ "userId": 16, "sendTime": "2018-03-06 12:04:15" }