spring MVC 中使用 MessageConverter 在遇到 @RequestBody 时,将请求体中的 json 字符串转换为java对象,遇到 @ResponseBody 时将方法返回值转换为 json 字符串作为请求响应内容。
有时我们想要修改 json 字符串的转换特性时(例如 null 值的处理,时间格式等) ,需要添加自定义的 MessageConverter。我平时使用 fastjson 比较多。
先来看看不用 fastjson 时的 样子
这个接口中,并没有返回 password 字段, 默认的 MessageConverter 将 null 值转换成了 "password": null 的形式。createTime 在 java 代码中是 date 类型,转换成了时间戳 timestamp。
使用 fastjson
引入依赖
之前的已经引入了,可以跳过
com.alibaba
fastjson
1.2.22
继承 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 中 Override configureMessageConverters 方法,新增内容如下
@Override
public void configureMessageConverters(List> converters) {
converters.add(fastJsonHttpMessageConverterEx());
super.configureMessageConverters(converters);
}
@Bean
public FastJsonHttpMessageConverterEx fastJsonHttpMessageConverterEx() {
return new FastJsonHttpMessageConverterEx();
}
配置完毕,重启项目,再来添加一篇文章试试。
原本为 null 的 password 字段不见了,可见 fastjson 默认是不转换 null 值的。fastjson 对日期的默认处理和spring MVC 默认的MessageConverter一样, createTime 还是时间戳 timestamp的格式。
配置 fastjson
接下来以转换 null 值和换一种时间格式(yyyy-MM-dd HH:mm:ss)为例看看怎么配置 fastjson。
在 FastJsonHttpMessageConverterEx.java 的构造方法中
public FastJsonHttpMessageConverterEx() {
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss"); // 自定义时间格式
fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue); // 正常转换 null 值
this.setFastJsonConfig(fastJsonConfig);
}
重启项目,再次添加一篇文章试试
null 值又回来啦,createTime 也变成了我们想要的样子。
SerializerFeature 那个类里面还有好多特性,可以点开看看。
在平时的开发中我比较喜欢 fastjson 默认的配置(不显示 null 值,使用时间戳 timestamp 表示时间),timestamp 形式的时间也方法客户端转换,虽然可读性方面差了点。
查看项目完整代码
git clone https://github.com/hyrijk/spring-boot-blog.git
checkout 到当前版本
git checkout d7365d85b21491f6746f7e08cc2ef5505751d082
完。