Spring Boot 配置fastjson

1.在pom.xml加入fastjson依賴html

<!-- fastjson依賴 -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.12</version>
</dependency>

2.建立mvc配置類WebMvcConfig繼承WebMvcConfigurerAdapterjava

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter  {

    private static final Logger logger = LoggerFactory.getLogger(WebMvcConfig.class);
}

3.添加fastjson相關設置的方法json

/**
	 * fastJson相關設置
	 */
	private FastJsonConfig getFastJsonConfig() {
		logger.debug("fastJsonConfig");
		
		FastJsonConfig fastJsonConfig = new FastJsonConfig();
        // 在serializerFeatureList中添加轉換規則
		List<SerializerFeature> serializerFeatureList = new ArrayList<SerializerFeature>();
		serializerFeatureList.add(SerializerFeature.WriteMapNullValue);
		serializerFeatureList.add(SerializerFeature.WriteNullStringAsEmpty);
		
		SerializerFeature[] serializerFeatures = serializerFeatureList.toArray(new SerializerFeature[serializerFeatureList.size()]);
		fastJsonConfig.setSerializerFeatures(serializerFeatures);

		return fastJsonConfig;
	}

4.對fastjson進行配置mvc

/**
	 * fastJson相關設置
	 */
	private FastJsonHttpMessageConverter4 fastJsonHttpMessageConverter() {
		logger.debug("fastJsonHttpMessageConverter");

		FastJsonHttpMessageConverter4 fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter4();

		List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
		supportedMediaTypes.add(MediaType.parseMediaType("text/html;charset=UTF-8"));
		supportedMediaTypes.add(MediaType.parseMediaType("application/json"));

		fastJsonHttpMessageConverter.setSupportedMediaTypes(supportedMediaTypes);
		fastJsonHttpMessageConverter.setFastJsonConfig(getFastJsonConfig());

		return fastJsonHttpMessageConverter;
	}

5.覆寫configureMessageConverters方法,將fastJsonHttpMessageConverter添加到converters中app

/**
	 * 添加fastJsonHttpMessageConverter到converters
	 */
	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		logger.debug("configureMessageConverters");

		converters.add(fastJsonHttpMessageConverter());
	}
相關文章
相關標籤/搜索