Springboot替换默认jackSon为fastJson过程

本文介绍如何在SpringBoot项目中将jackJson替换为fastJson,包括两种配置方式:通过实现WebMvcConfigurerAdapter(适用于SpringBoot2.0之前)和直接配置JavaBean(适用于SpringBoot2.0及以上)。文中详细说明了配置步骤及注意事项。

因为工作原因,需要将jackJson替换为fastJson。
先说过程Springboot2.0以前的写法:

第一种:通过在启动类中实现WebMvcConfigurerAdapter 并重写ConfigureMessageConverters方法

第一步: pom.xml 中引用fastjson

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

第二步: 启动类中配置

@SpringBootApplication  //申明让spring boot自动给程序进行必要的配置
public class AppStart extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(AppStart.class, args);
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.PrettyFormat, 
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullNumberAsZero, 
                SerializerFeature.WriteNullStringAsEmpty
            );
        // 处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);
        fastConverter.setFastJsonConfig(fastJsonConfig);

        //处理字符串, 避免直接返回字符串的时候被添加了引号
        StringHttpMessageConverter smc = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        converters.add(smc);

        converters.add(fastConverter);
    }
}    

第二种:通过在启动类中配置JavaBean

在启动类中直接以JavaBean的形式进行配置

@SpringBootApplication  //申明让spring boot自动给程序进行必要的配置
public class AppStart extends WebMvcConfigurerAdapter {

	@Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        // 1.定义一个converters转换消息的对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        // 2.添加fastjson的配置信息,比如: 是否需要格式化返回的json数据
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        // 3.在converter中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);
        // 4.将converter赋值给HttpMessageConverter
        HttpMessageConverter<?> converter = fastConverter;
        // 5.返回HttpMessageConverters对象
        return new HttpMessageConverters(converter);
    }
    
    public static void main(String[] args) {
        SpringApplication.run(AppStart.class, args);
    }
}    

Springboot2.0以后,WebMvcConfigurerAdapter 过时了,原因是Springboot2.0最低支持JDK1.8,引入了新的default关键字,该关键字配置在interface接口的方法时子类可以不去实现该方法,相当于抽象类内已经实现的接口方法。新的代替方法是:直接实现WebMvcConfigurer或者实现WebMvcConfigurationSupport

### 如何在Spring Boot项目中替换FastJSON 在Spring Boot项目中,如果需要替换默认使用的序列化库(如FastJSON),可以采用其他流行的序列化工具来完成这一需求。以下是关于如何使用Jackson或其他序列化框架作为替代方案的具体方法。 #### 使用Jackson作为序列化器 Jackson是一个广泛使用的Java JSON处理库,默认情况下它也是Spring Boot中的首选序列化/反序列化工具之一。为了确保不使用FastJSON并切换到Jackson,可以通过以下方式配置: 1. **移除FastJSON依赖** 首先,在`pom.xml`文件中删除任何与FastJSON相关的依赖项。 2. **引入Jackson核心依赖** 如果尚未包含Jackson的核心依赖,则可以在Maven项目的`pom.xml`中添加如下内容: ```xml <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> ``` 3. **全局配置对象映射器** 可以通过自定义`ObjectMapper` Bean来自定义Jackson的行为。例如: ```java import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class JacksonConfig { @Bean public ObjectMapper objectMapper() { return new ObjectMapper(); } } ``` 4. **禁用FastJSON自动装配** 确保Spring Boot不会加载FastJSON的相关组件。这通常意味着要排除某些可能隐含启用它的starter包。 #### 使用Gson作为序列化器 除了Jackson之外,还可以考虑Google提供的[Gson](https://github.com/google/gson),这是一个轻量级但功能强大的JSON解析库。 1. 添加Gson依赖至`pom.xml`: ```xml <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </dependency> ``` 2. 自定义HttpMessageConverter以便支持Gson: 创建一个新的类用于注册Gson转换器: ```java import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.AbstractJsonHttpMessageConverter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.List; @Configuration public class GsonWebConfig implements WebMvcConfigurer { private final Gson gson = new GsonBuilder().create(); @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(new AbstractJsonHttpMessageConverter() { protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException { return gson.fromJson(new InputStreamReader(inputMessage.getBody()), clazz); } protected void writeInternal(Object o, Type typeOfSrc, HttpOutputMessage outputMessage) throws IOException { Writer writer = new OutputStreamWriter(outputMessage.getBody()); gson.toJson(o, typeOfSrc, writer); writer.flush(); } }); } } ``` 以上两种方法都可以有效实现从FastJSON向更安全可靠的解决方案迁移的目的[^1]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值