spring boot 配置fastjson

本文介绍了如何在Spring Boot项目中替换默认的Jackson,使用Fastjson作为JSON转换工具。首先,需要引入Fastjson 1.2.10+版本的jar。接着,提供了两种配置方式:一是通过继承`WebMvcConfigurationSupport`并覆盖`configureMessageConverters`方法;二是通过注入`HttpMessageConverters` Bean来实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

spring boot 默认使用的json转换工具是jackson。

集成fastjson,引入fastjson的jar,版本1.2.10+

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.15</version>
        </dependency>

配置fastjson有两种方式

第一种方式: 
① 启动类继承 WebMvcConfigurerAdapter (已过时),改用WebMvcConfigurationSupport
②覆盖configureMessageConverters方法

@SpringBootApplication
public class App extends WebMvcConfigurationSupport{

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		super.configureMessageConverters(converters);
		/**
		 * 1.需要先定义一个convert 转换消息的对象;
		 * 2.添加fastjson 的配置信息,比如:是否要转换格式化返回的json数据;
		 * 3.在convert中添加配置信息
		 * 4.将convert添加到converters当中
		 */
		// 1.需要先定义一个convert 转换消息的对象;
		FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
		//2.添加fastjson 的配置信息,比如:是否要转换格式化返回的json数据;
		FastJsonConfig fastJsonConfig = new FastJsonConfig();
		fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
		//3.在convert中添加配置信息
		fastConverter.setFastJsonConfig(fastJsonConfig);
		//4.将convert添加到converters当中
		converters.add(fastConverter);
    }

第二种方式: 
启动类注入Bean HttpMessageConverters

@Bean
public HttpMessageConverters fastjsonHttpMessageConverter(){
        //定义一个转换消息的对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

        //添加fastjson的配置信息 比如 :是否要格式化返回的json数据
        FastJsonConfig fastJsonConfig = new FastJsonConfig();

        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);

        //在转换器中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);

        HttpMessageConverter<?> converter = fastConverter;

        return new HttpMessageConverters(converter);

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Z涛子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值