如何在Spring Boot中使用FastJson
隨著Spring Boot的發(fā)展,WebMvcConfigurerAdapter類已經被棄用了。因此,在這里我們需要使用WebMvcConfigurationSupport類來配置FastJson。一
隨著Spring Boot的發(fā)展,WebMvcConfigurerAdapter類已經被棄用了。因此,在這里我們需要使用WebMvcConfigurationSupport類來配置FastJson。
一、新建類,并繼承WebMvcConfigurationSupport
為了使用FastJson,我們需要自己編寫一個配置類并繼承WebMvcConfigurationSupport類。這個類是Spring Boot提供的,它能夠代替之前的WebMvcConfigurerAdapter類。代碼如下:
```java
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
}
```
二、重寫configureMessageConverters方法
我們需要在WebMvcConfigurationSupport類中重寫configureMessageConverters方法,并在其中加入FastJsonHttpMessageConverter轉換器。
```java
@Override
protected void configureMessageConverters(List
FastJsonHttpMessageConverter fastJsonHttpMessageConverter new FastJsonHttpMessageConverter();
(fastJsonHttpMessageConverter);
}
```
三、配置FastJsonHttpMessageConverter
我們還需要在configureMessageConverters方法中加入如下代碼:
```java
FastJsonHttpMessageConverter fastJsonHttpMessageConverter new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig new FastJsonConfig();
// 配置序列化后的輸出格式
// DisableCircularReferenceDetect:消除對同一對象循環(huán)引用的問題,默認為false,此項如果不配置有可能會進入死循環(huán)
// WriteMapNullValue:是否輸出值為null的字段,默認為false,即不輸出,設置后可以輸出值為null的字段
// WriteNullStringAsEmpty:字符類型字段如果為null,則輸出為""
(SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty);
// 下面兩三行解決fastjson中文亂碼問題
List
(_JSON_UTF8);
(fastJsonMediaType);
(fastJsonConfig);
(fastJsonHttpMessageConverter);
```
通過以上步驟,我們就成功地配置了FastJson。現在我們可以愉快地使用它了哦!