欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 前端技术 > javascript >内容正文

javascript

SpringBoot学习之路:06.Spring Boot替换默认的Jackson

发布时间:2024/1/17 javascript 47 豆豆
生活随笔 收集整理的这篇文章主要介绍了 SpringBoot学习之路:06.Spring Boot替换默认的Jackson 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

2019独角兽企业重金招聘Python工程师标准>>>

       SpringBoot和Springmvc都可以返回接送数据,SpringBoot默认是使用Jackson解析json数据的,个人觉得阿里的Fastjson性能更好点,API使用更方便,于是将SpringBoot默认的Jackson替换成阿里的Fastjson。

一.配置类注入的方式

package com.maxbill.core.config.json;import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import org.springframework.boot.autoconfigure.web.HttpMessageConverters; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter;/*** @功能 JSON解析器配置* @作者 zuoshuai(MaxBill)* @日期 2017/7/6* @时间 12:24* @备注 替换默认的json框架,替换成阿里的fastjson*/ @Configuration public class JsonConfig {@Beanpublic HttpMessageConverters fastJsonHttpMessageConverters() {FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();FastJsonConfig fastJsonConfig = new FastJsonConfig();fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);fastConverter.setFastJsonConfig(fastJsonConfig);HttpMessageConverter<?> converter = fastConverter;return new HttpMessageConverters(converter);}}

二.配置类继承WebMvcConfigurerAdapter覆盖方法

package com.maxbill.core.config.json;import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;import java.util.List;/*** @功能 JSON解析器配置* @作者 zuoshuai(MaxBill)* @日期 2017/7/6* @时间 12:35* @备注 替换默认的json框架,替换成阿里的fastjson*/ @Configuration public class JsonConfigBack extends WebMvcConfigurerAdapter {@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {super.configureMessageConverters(converters);FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();FastJsonConfig fastJsonConfig = new FastJsonConfig();fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);fastConverter.setFastJsonConfig(fastJsonConfig);converters.add(fastConverter);}}

注意:记得引入Fastjson的依赖包;在1.2.10版本以后有两个方法支持HttpMessageconvert了

一:FastJsonHttpMessageConverter,支持4.2以下的版本;

二:FastJsonHttpMessageConverter4支持4.2以上的版本。

所以Fastjson需要在1.2.10版本以上。

转载于:https://my.oschina.net/zss1993/blog/1186502

总结

以上是生活随笔为你收集整理的SpringBoot学习之路:06.Spring Boot替换默认的Jackson的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。