fastJson使用比较多。用起来顺手。所以想把jackson替换掉。
- 引入最新fastjson。maven引入不用多说啦。
- 新建类,继承自
WebMvcConfigurerAdapter
,重写extendMessageConverters
方法。
import com.alibaba.fastjson.serializer.SerializerFeature
import com.alibaba.fastjson.support.config.FastJsonConfig
import org.springframework.context.annotation.Configuration
import org.springframework.http.converter.HttpMessageConverter
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter
import org.springframework.boot.SpringBootConfiguration
import org.springframework.http.MediaType
import org.springframework.web.servlet.config.annotation.EnableWebMvc
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
@SpringBootConfiguration
@EnableWebMvc
open class WebMvcConfigFastJson : WebMvcConfigurerAdapter(){
/**
* 这里是kotlin的语法。java基本一样。
*/
override fun extendMessageConverters(converters: MutableList<HttpMessageConverter<*>>) {
super.extendMessageConverters(converters)
//这里把springBoot依赖的jackson去掉。
//如果没有其他包依赖jackson,也可以直接pom里把jackson去掉
converters.removeIf({ httpMessageConverter -> httpMessageConverter is MappingJackson2HttpMessageConverter })
val converter:FastJsonHttpMessageConverter = FastJsonHttpMessageConverter()
var config:FastJsonConfig = FastJsonConfig()
config.dateFormat = "yyyy-MM-dd HH:mm:ss"
config.setSerializerFeatures(
SerializerFeature.BrowserSecure
,SerializerFeature.WriteBigDecimalAsPlain
,SerializerFeature.WriteEnumUsingToString
,SerializerFeature.WriteDateUseDateFormat)
//处理中文乱码问题
var fastMediaTypes:ArrayList<MediaType> = ArrayList<MediaType>()
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8)
converter.setSupportedMediaTypes(fastMediaTypes)
converter.setFastJsonConfig(config)
converters.add(converter)
}
}
这里是pom.xml去掉jackson
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
然后就可以开心的使用的fastjson了
参阅:
- Spring Boot使用Gson替换Jackson【http://blog.gelu.me/2017/spring-boot-uses-gson-to-replace-jackson/】
- SpringMVC中使用@RequestBody,@ResponseBody注解实现Java对象和XML/JSON数据自动转换(上)【http://blog.csdn.net/fw0124/article/details/48280083】
- spring boot(2)-@SpringBootApplication详解【http://blog.csdn.net/wangb_java/article/details/70943500?utm_source=itdadao&utm_medium=referral】