Springboot2.x整合fastjson

Springboot2.x整合fastjson

SpringBoot2.0如何集成fastjson?在网上查了一堆资料,但是各文章的说法不一,有些还是错的,可能只是简单测试一下就认为ok了,最后有没生效都不知道。恰逢公司项目需要将JackSon换成fastjson,因此自己来实践一下SpringBoot2.0和fastjson的整合,同时记录下来方便自己后续查阅。

一、Maven依赖说明

SpringBoot的版本为: 2.1.4.RELEASE
在pom文件中添加fastjson的依赖:

 <!-- fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.56</version>
        </dependency>

二、整合

我们写一个配置类WebConfig实现WebMvcConfigurer接口,然后重写configureMessageConverters方法。具体的代码如下:

import cn.jiangdoc.web.interceptor.AuthorizationInterceptor;
import cn.jiangdoc.web.interceptor.LoginInterceptor;
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.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
 
    /**
     * 使用fastjson代替jackson
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    /*
     先把JackSon的消息转换器删除.
     备注: (1)源码分析可知,返回json的过程为:
                Controller调用结束后返回一个数据对象,for循环遍历conventers,找到支持application/json的HttpMessageConverter,然后将返回的数据序列化成json。
                具体参考org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor的writeWithMessageConverters方法
           (2)由于是list结构,我们添加的fastjson在最后。因此必须要将jackson的转换器删除,不然会先匹配上jackson,导致没使用fastjson
    */
        for (int i = converters.size() - 1; i >= 0; i--) {
            if (converters.get(i) instanceof MappingJackson2HttpMessageConverter) {
                converters.remove(i);
            }
        }
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        //自定义fastjson配置
        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(
                SerializerFeature.WriteMapNullValue,        // 是否输出值为null的字段,默认为false,我们将它打开
                SerializerFeature.WriteNullListAsEmpty,     // 将Collection类型字段的字段空值输出为[]
                SerializerFeature.WriteNullStringAsEmpty,   // 将字符串类型字段的空值输出为空字符串
                SerializerFeature.WriteNullNumberAsZero,    // 将数值类型字段的空值输出为0
                SerializerFeature.WriteDateUseDateFormat,
                SerializerFeature.DisableCircularReferenceDetect    // 禁用循环引用
        );
        fastJsonHttpMessageConverter.setFastJsonConfig(config);
        // 添加支持的MediaTypes;不添加时默认为*/*,也就是默认支持全部
        // 但是MappingJackson2HttpMessageConverter里面支持的MediaTypes为application/json
        // 参考它的做法, fastjson也只添加application/json的MediaType
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
        converters.add(fastJsonHttpMessageConverter);
    }
}

三、测试

(1)代码
要测试fastjson是否整合成功的话,我们只需要在实体类中使用一下fastjson的注解就ok。如果注解生效了,说明fastjson整合成功了。直接看代码

import com.alibaba.fastjson.annotation.JSONField;
import com.psx.gqxy.common.base.ModelResult;
import lombok.Data;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.List;

@RestController
public class TestController {
    @GetMapping("/json")
    public ModelResult<JsonBean> testJson() {
        ModelResult<JsonBean> result = new ModelResult<>();
        JsonBean jsonBean = new JsonBean();
        jsonBean.setBirthDay(new Date());
        jsonBean.setName("测试");
        result.setData(jsonBean);
        return result;
    }
	
    @Data
    class JsonBean {
        private String name;
        @JSONField(format = "yyyy年MM月dd日")
        private Date birthDay;
        private List<String> qqList;
    }
}

(2)效果
在这里插入图片描述
通过这个2步的测试,发现fastjson的注解生效了,也就说明整合成功了

四、杂谈

SpringBoot2.0后,有些东西改变了。在SpringBoot 1.X时代,整合fastjson是可以不排除JackSon消息转换器的。但在SpringBoot2.X时代,必须要排除JackSon消息转换器。

Spring Boot提供了一种简单的方式来处理全局异常,并且它可以与Fastjson进行整合。 在Spring Boot中,我们可以通过定义一个`@ControllerAdvice`注解的异常处理类来处理全局异常。该注解表示这个类是一个全局异常处理类。在这个类中,我们可以定义多个`@ExceptionHandler`注解的方法来处理不同类型的异常。 首先,我们需要在pom.xml文件中添加Fastjson的依赖。在`<dependencies>`标签中加入以下代码: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency> ``` 接下来,我们创建一个全局异常处理类,命名为`GlobalExceptionHandler`。在该类上添加`@RestControllerAdvice`注解,这样我们就可以在方法中返回JSON格式的错误信息。 在`GlobalExceptionHandler`类中,我们可以定义多个方法来处理不同类型的异常。例如,我们可以通过`@ExceptionHandler(Exception.class)`来处理所有类型的异常。在这个方法中,我们可以将异常信息封装成一个`ErrorResponse`对象,并将其转换为JSON字符串。 以下是一个使用Fastjson进行全局异常处理的例子: ```java @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public String handleException(Exception e) { ErrorResponse errorResponse = new ErrorResponse(); errorResponse.setCode(500); errorResponse.setMessage("Internal Server Error"); // 将ErrorResponse对象转换为JSON字符串 return JSON.toJSONString(errorResponse); } } ``` 在上述代码中,`GlobalExceptionHandler`类中的`handleException`方法会处理所有类型的异常,并将异常信息封装成一个`ErrorResponse`对象。最后,通过`JSON.toJSONString`方法将`ErrorResponse`对象转换为JSON字符串。 这样,当发生异常时,Spring Boot会自动调用`GlobalExceptionHandler`类中的相应方法并返回JSON格式的错误信息。整合Fastjson后,我们可以更方便地处理异常信息并返回自定义的错误响应。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值