foreword
Recently, due to project needs, I rebuilt a set of frameworks from scratch for colleagues to use. When the front-end and back-end are connected, it is found that the fields provided by the back-end are missing a lot, that is, the fields with entity classes with null values are all filtered out. After investigation, it is the fault of fastjson.
Because fastjson filters out values whose value is null by default, and does not output null values.
As the saying goes, when you encounter a problem, find the cause of the problem, and half of your problem has been solved.
environment:
-
jdk1.8
-
maven:3.6.3
-
spring boot:2.2.13-RELEASE
-
fastjson:1.28.0
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.80</version>
</dependency>
Solution
The solution is also very simple, just add a configuration file to annotate fastjson configuration.
Among them, the most important thing is to configure the functions of fastJson through the setSerializerFeatures method of FastJsonConfig
com.alibaba.fastjson.support.config.FastJsonConfig#setSerializerFeatures
/**
* 返回值过滤器
*
* @Author: 攻城狮白玉 https://blog.csdn.net/zhh763984017
* @Date: 2022/7/09 18:05
*/
@Configuration
public class FastjsonConverterConfig {
@Bean
public HttpMessageConverters customConverters() {
// 定义一个转换消息的对象
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
// 添加fastjson的配置信息 比如 :是否要格式化返回的json数据
FastJsonConfig fastJsonConfig = new FastJsonConfig();
// 这里就是核心代码了,WriteMapNullValue把空的值的key也返回
fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue);
List<MediaType> fastMediaTypes = new ArrayList<MediaType>();
// 处理中文乱码问题
fastJsonConfig.setCharset(Charset.forName("UTF-8"));
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastConverter.setSupportedMediaTypes(fastMediaTypes);
// 在转换器中添加配置信息
fastConverter.setFastJsonConfig(fastJsonConfig);
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
stringConverter.setDefaultCharset(Charset.forName("UTF-8"));
stringConverter.setSupportedMediaTypes(fastMediaTypes);
// 将转换器添加到converters中
return new HttpMessageConverters(stringConverter,fastConverter);
}
}
postscript
It is really not easy to build a new framework from scratch.
Although the original framework has more dependencies and is a bit heavier, there are also many old configurations, which is very fragrant.
However, rebuilding the new framework also made me re-examine a lot of knowledge. For the construction and use of the framework, when it is time to use Occam's razor, I have to use Occam's razor to keep the framework as clean as possible.