spring MVC 中使用 MessageConverter 在遇到 @RequestBody 時(shí),將請求體中的 json 字符串轉(zhuǎn)換為java對象,遇到 @ResponseBody 時(shí)將方法返回值轉(zhuǎn)換為 json 字符串作為請求響應(yīng)內(nèi)容。
有時(shí)我們想要修改 json 字符串的轉(zhuǎn)換特性時(shí)(例如 null 值的處理,時(shí)間格式等) ,需要添加自定義的 MessageConverter。我平時(shí)使用 fastjson 比較多。
先來看看不用 fastjson 時(shí)的 樣子

這個(gè)接口中,并沒有返回
password 字段, 默認(rèn)的 MessageConverter 將 null 值轉(zhuǎn)換成了 "password": null 的形式。createTime 在 java 代碼中是 date 類型,轉(zhuǎn)換成了時(shí)間戳 timestamp。
使用 fastjson
- 引入依賴
之前的已經(jīng)引入了,可以跳過
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.22</version>
</dependency>
- 繼承
FastJsonHttpMessageConverter
在config包中新建 FastJsonHttpMessageConverterEx.java
public class FastJsonHttpMessageConverterEx extends FastJsonHttpMessageConverter {
public FastJsonHttpMessageConverterEx() {
// 在這里配置 fastjson 特性
}
@Override
protected boolean supports(Class<?> clazz) {
return super.supports(clazz);
}
}
- 配置
FastJsonHttpMessageConverterEx
在 WebMvcConfigurer.java 中 OverrideconfigureMessageConverters方法,新增內(nèi)容如下
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(fastJsonHttpMessageConverterEx());
super.configureMessageConverters(converters);
}
@Bean
public FastJsonHttpMessageConverterEx fastJsonHttpMessageConverterEx() {
return new FastJsonHttpMessageConverterEx();
}
配置完畢,重啟項(xiàng)目,再來添加一篇文章試試。

原本為
null 的 password 字段不見了,可見 fastjson 默認(rèn)是不轉(zhuǎn)換 null 值的。fastjson 對日期的默認(rèn)處理和spring MVC 默認(rèn)的MessageConverter一樣, createTime 還是時(shí)間戳 timestamp的格式。
配置 fastjson
接下來以轉(zhuǎn)換 null 值和換一種時(shí)間格式(yyyy-MM-dd HH:mm:ss)為例看看怎么配置 fastjson。
在 FastJsonHttpMessageConverterEx.java 的構(gòu)造方法中
public FastJsonHttpMessageConverterEx() {
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss"); // 自定義時(shí)間格式
fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue); // 正常轉(zhuǎn)換 null 值
this.setFastJsonConfig(fastJsonConfig);
}
重啟項(xiàng)目,再次添加一篇文章試試

null 值又回來啦,createTime 也變成了我們想要的樣子。SerializerFeature 那個(gè)類里面還有好多特性,可以點(diǎn)開看看。在平時(shí)的開發(fā)中我比較喜歡 fastjson 默認(rèn)的配置(不顯示
null 值,使用時(shí)間戳 timestamp 表示時(shí)間),timestamp 形式的時(shí)間也方法客戶端轉(zhuǎn)換,雖然可讀性方面差了點(diǎn)。
查看項(xiàng)目完整代碼
項(xiàng)目地址: https://github.com/hyrijk/spring-boot-blog
克隆項(xiàng)目到本地
git clone https://github.com/hyrijk/spring-boot-blog.git
checkout 到當(dāng)前版本
git checkout d7365d85b21491f6746f7e08cc2ef5505751d082
完。