springboot配置fastjson以及jackson(避坑)

本文详细介绍了如何在Spring Boot项目中配置Fastjson和Jackson,包括接口返回格式化与Redis序列化的具体步骤,帮助开发者避免常见问题。

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

1、fastjson配置

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>jackson-databind</artifactId>
                    <groupId>com.fasterxml.jackson.core</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.2</version>
        </dependency>

1.1 接口返回格式化配置

import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ToStringSerializer;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    /**
     * fastjson配置
     * <p>
     * 1.先定义一个convert转换消息的对象
     * 2.添加fastjson的配置信息,比如:是否要格式化返回的json数据
     * 3.在convert中添加配置信息
     * 4.将convert添加到converters当中
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //1.先定义一个convert转换消息的对象
        FastJsonHttpMessageConverter fasHttpMessageConverter = new FastJsonHttpMessageConverter();
        //处理中文乱码问题(不然出现中文乱码)
        List<MediaType> fastMediaTypes = new ArrayList<MediaType>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON);
        fastMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
        fastMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
        fastMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
        fastMediaTypes.add(MediaType.APPLICATION_PDF);
        fastMediaTypes.add(MediaType.APPLICATION_RSS_XML);
        fastMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
        fastMediaTypes.add(MediaType.APPLICATION_XML);
        fastMediaTypes.add(MediaType.IMAGE_GIF);
        fastMediaTypes.add(MediaType.IMAGE_JPEG);
        fastMediaTypes.add(MediaType.IMAGE_PNG);
        fastMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
        fastMediaTypes.add(MediaType.TEXT_HTML);
        fastMediaTypes.add(MediaType.TEXT_MARKDOWN);
        fastMediaTypes.add(MediaType.TEXT_XML);
        fastMediaTypes.add(new MediaType("application", "vnd.spring-boot.actuator.v2+json"));
        fastMediaTypes.add(new MediaType("application", "vnd.spring-boot.actuator.v1+json"));
        fastMediaTypes.add(new MediaType("application", "vnd.spring-boot.actuator.v3+json"));
        fasHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);

        //2.添加fastjson的配置信息,比如:是否要格式化返回的json数据
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.PrettyFormat,
                // 保留 Map 空的字段
                SerializerFeature.WriteMapNullValue,
                // 将 String 类型的 null 转成""
                SerializerFeature.WriteNullStringAsEmpty,
                // 将 Number 类型的 null 转成 0
                SerializerFeature.WriteNullNumberAsZero,
                // 将 List 类型的 null 转成 []
                SerializerFeature.WriteNullListAsEmpty,
                // 将 Boolean 类型的 null 转成 false
                SerializerFeature.WriteNullBooleanAsFalse,
                // 避免循环引用
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteBigDecimalAsPlain
        );
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        fastJsonConfig.setCharset(StandardCharsets.UTF_8);
        //解决Long转json精度丢失的问题
        SerializeConfig serializeConfig = SerializeConfig.globalInstance;
        serializeConfig.put(BigDecimal.class, ToStringSerializer.instance);
        serializeConfig.put(Double.class, ToStringSerializer.instance);
        serializeConfig.put(Integer.class, ToStringSerializer.instance);
        serializeConfig.put(BigInteger.class, ToStringSerializer.instance);
        serializeConfig.put(Long.class, ToStringSerializer.instance);
        serializeConfig.put(Long.TYPE, ToStringSerializer.instance);
        fastJsonConfig.setSerializeConfig(serializeC
### Spring Boot 整合 FastJSON 示例及配置方法 #### 添加 Maven 依赖 为了在 Spring Boot 中使用 FastJSON 进行 JSON 处理,首先需要在项目的 `pom.xml` 文件中引入 FastJSON 的依赖项。以下是具体的依赖配置: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.78</version> </dependency> ``` 上述代码片段展示了如何通过 Maven 构建工具来添加 FastJSON 到项目中[^2]。 --- #### 自定义 MessageConverter 配置 Spring Boot 默认使用 Jackson 来处理 JSON 数据转换。如果希望切换到 FastJSON,则需要自定义消息转换器 (`HttpMessageConverter`) 并将其注册到 Spring MVC 容器中。可以通过创建一个配置类来完成此操作: ```java import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import java.util.List; @Configuration public class WebConfig { @Bean public HttpMessageConverter<?> fastJsonHttpMessageConverter() { // 创建 FastJsonHttpMessageConverter 实例 FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); // 初始化并设置 FastJsonConfig 参数 FastJsonConfig config = new FastJsonConfig(); config.setSerializerFeatures( com.alibaba.fastjson.serializer.SerializerFeature.PrettyFormat, com.alibaba.fastjson.serializer.SerializerFeature.WriteMapNullValue); converter.setFastJsonConfig(config); return converter; } /** * 替换默认的消息转换器为 FastJSON 版本。 */ public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(fastJsonHttpMessageConverter()); } } ``` 以上代码实现了将 FastJSON 设置为默认的 JSON 解析库的功能,并允许开发者进一步调整序列化行为[^1]。 --- #### 测试 FastJSON 功能 假设我们有一个简单的控制器用于返回 JSON 数据,可以验证 FastJSON 是否正常工作。例如: ```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") public class UserController { @GetMapping("/user") public User getUser() { User user = new User(); user.setUsername("JohnDoe"); user.setBirthday(new Date()); return user; } } class User { private String username; private Date birthday; // Getter 和 Setter 方法省略 } ``` 当访问 `/api/user` 接口时,应该可以看到由 FastJSON 生成的标准 JSON 响应数据[^4]。 --- #### 注意事项 - **版本兼容性**:确保使用的 FastJSON 版本与当前环境匹配,免潜在的安全漏洞或功能缺失问题。 - **性能优化**:对于大规模生产应用,建议评估不同 JSON 库之间的性能差异后再决定采用哪种方案。 - **安全性考量**:由于历史上存在一些关于 FastJSON 的安全风险报告,在实际部署前需仔细审查其最新补丁状态。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

菜鸟程序员a

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

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

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

打赏作者

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

抵扣说明:

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

余额充值