作者: | 来源:互联网 | 2023-09-14 17:08
篇首语:本文由编程笔记#小编为大家整理,主要介绍了springboot2.0添加对fastjson的支持相关的知识,希望对你有一定的参考价值。首先引入fastjson
篇首语:本文由编程笔记#小编为大家整理,主要介绍了spring boot 2.0添加对fastjson的支持相关的知识,希望对你有一定的参考价值。
首先引入fastjson的maven依赖:
com.alibaba
fastjson
1.2.31
然后添加一个配置类:
package com.boot.demo;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import javafx.scene.chart.Chart;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Bean;
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.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@Configuration
public class FastJsonConfiguration implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List> converters) {
/**
* 先移除MappingJackson2HttpMessageConverter转换器,再加入fastjson转换器
*/
Iterator> iterator = converters.iterator();
while(iterator.hasNext()){
HttpMessageConverter> cOnverter= iterator.next();
if(converter instanceof MappingJackson2HttpMessageConverter){
iterator.remove();
}
}
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
//自定义配置...
FastJsonConfig cOnfig= new FastJsonConfig();
config.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteMapNullValue
,SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullBooleanAsFalse,
SerializerFeature.WriteNullStringAsEmpty,SerializerFeature.WriteNullNumberAsZero);
fastJsonHttpMessageConverter.setFastJsonConfig(config);
//解决返回的json数据中文乱码问题
List fastMediaTypes = new ArrayList();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
//将转换器添加到转换列表
converters.add(fastJsonHttpMessageConverter);
}
}