idea创建一个SpringBoot项目
在pom文件中添加依赖
创建FastJsonConfiguration配置信息类
由于WebMvcConfigurerAdapter在Spring5已被废弃,查看源码可知,只是WebMvcConfigurer接口的一个空实现
可直接实现WebMvcConfigurer这个接口
实现如下:
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.List;
/**
* @author T_liu
* @Title: FastJsonConfiguration
* @ProjectName sbdemo
* @Description: fastjson配置
* @date 2018/11/3 8:39
*/
@Configuration
public class FastJsonConfiguration implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//创建配置类
FastJsonConfig config = new FastJsonConfig();
//创建fastjson消息转换器
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
//常用的SerializerFeatures配置
config .setSerializerFeatures(
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullBooleanAsFalse,
SerializerFeature.WriteNullNumberAsZero
);
List<MediaType> mediaType = new ArrayList<>();
fastMediaType.add(MediaType.APPLICATION_JSON_UTF8);
fastConverter.setSupportedMediaTypes(mediaType);
fastConverter.setFastJsonConfig(config );
//将fastjson添加到视图消息转换器
converters.add(fastConverter);
}
}