import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring.http.converter.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
/**
* @Description 重写configureMessageConverters转换器对返回值内容进行转换
* @Author WangKun
* @Date 2023/4/10 16:27
* @Version
*/
@Configuration
public class FastJson2Config implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//字符串转换
StringHttpMessageConverter strConverter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
converters.add(strConverter);
//定义一个convert转换消息的对象
FastJsonHttpMessageConverter fastConverter=new FastJsonHttpMessageConverter();
//添加fastjson的配置信息,比如是否要格式化返回的json数据;
FastJsonConfig config = new FastJsonConfig();
config.setWriterFeatures(
//是否输出值为null的字段,默认为false
JSONWriter.Feature.WriteMapNullValue,
//将Collection类型字段的字段空值输出为[]
JSONWriter.Feature.WriteNullListAsEmpty,
//将字符串类型字段的空值输出为空字符串
JSONWriter.Feature.WriteNullStringAsEmpty,
// 将Number类型的null转成0
JSONWriter.Feature.WriteNullNumberAsZero,
// 将Boolean类型的null转成false
JSONWriter.Feature.WriteNullBooleanAsFalse
);
config.setDateFormat("yyyy-MM-dd HH:mm:ss");
//在convert中添加配置信息
fastConverter.setFastJsonConfig(config);
//设置支持的媒体类型
fastConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));
//设置默认字符集
fastConverter.setDefaultCharset(StandardCharsets.UTF_8);
//将convert添加到converters
converters.add(fastConverter);
}
}
版权声明:本文为WangKun_0612原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。