Springboot项目中使用FastJson注解@JSONField(serialize = false)无效
一、问题出现场景
在controller层将实体类的list集合放入ModelMap中,方法通过@ResponseBody注解进行转json串返回给视图
二、发生问题
在视图中查看当前获取的json串,发现加上@JSONField(serialize = false)注解的字段也被序列化出来了。
三、分析原因
Sprintboot默认是通过jackson来转换JSON的,@JSONField(serialize = false)是FastJson的注解,Springboot使用jackson进行转JSON的时候并不会扫描这个注解。
四、解决方法
在Springboot启动类中添加如下配置
@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);
}