Spring Boot配置FastJson做为JSON解析框架

Spring Boot有自带的JSON解析框架,但自带的JSON解析框架有时候无法满足我们的需求,FastJson是一种比较流行的JSON解析框架,下面整理一下Spring Boot配置FastJson做为JSON解析框架的两种方法。

首先,要在pom.xml中引入FastJson依赖,配置如下

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

方法一、通过继承WebMvcConfigurerAdapter的方式
将Spring Boot启动类继承WebMvcConfigurerAdapter,并且重写configureMessageConverters方法,核心代码如下:

@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        System.out.println("Spring Boot start successful!!");
    }

    /**
     * 引入FastJson第一种方式:继承WebMvcConfigurerAdapter,重写configureMessageConverters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        // 1.定义一个消息转换器对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        // 2.定义FastJson配置对象,并且配置对应的属性
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        // 3.FastJson配置放入消息转换器对象中
        fastConverter.setFastJsonConfig(fastJsonConfig);
        // 4.消息转换器对象添加到消息转换器list
        converters.add(fastConverter);
    }
}

以上配置完成之后就可以使用FastJson相关功能了,比如我在下图中两个属性上分别使用了FastJson的注解:
在这里插入图片描述
如上图,name属性因为使用FastJosn注解就不会被序列化,birthday属性序列化会按照yyyy-MM-dd HH:mm:ss格式输出,如:2020-03-01 23:10:10。
这样启动spring boot服务后就能达到我们想要的JSON解析效果。

方法二、通过@Bean注入的方式
在Spring Boot启动类中自定义FastJson消息转换器方法,并通过@Bean注入到Spring Boot容器中,核心代码如下:

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        System.out.println("Spring Boot start successful!!");
    }

    /**
     * 引入FastJson第二种方式:自定义方法,Bean注入
     *
     * @return
     */
    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverter() {
        // 1.定义一个消息转换器对象
        FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter();
        // 2.定义FastJson配置对象,并且配置对应的属性
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        // 3.FastJson配置放入消息转换器对象中
        fastJsonConverter.setFastJsonConfig(fastJsonConfig);
        // 4.将消息转换器对象添加到消息转换器list中并返回
        return new HttpMessageConverters(fastJsonConverter);
    }
}

以上为Spring Boot配置FastJson做为JSON解析框架的两种方法。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值