spring boot 2.0添加对fastjson的支持

Posted Mr. Ma

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring boot 2.0添加对fastjson的支持相关的知识,希望对你有一定的参考价值。

首先引入fastjson的maven依赖:

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

  然后添加一个配置类:

package com.boot.demo;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import javafx.scene.chart.Chart;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Bean;
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.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Configuration
public class FastJsonConfiguration implements WebMvcConfigurer {


    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

        /**
         * 先移除MappingJackson2HttpMessageConverter转换器,再加入fastjson转换器
         */
        Iterator<HttpMessageConverter<?>> iterator = converters.iterator();
        while(iterator.hasNext()){
            HttpMessageConverter<?> converter = iterator.next();
            if(converter instanceof MappingJackson2HttpMessageConverter){
                iterator.remove();
            }
        }
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        //自定义配置...
        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteMapNullValue
                ,SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullStringAsEmpty,SerializerFeature.WriteNullNumberAsZero);
        fastJsonHttpMessageConverter.setFastJsonConfig(config);

        //解决返回的json数据中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<MediaType>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);

        //将转换器添加到转换列表
        converters.add(fastJsonHttpMessageConverter);

    }

}

 

以上是关于spring boot 2.0添加对fastjson的支持的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot 2.0:使用 Docker 部署 Spring Boot

Spring Boot 2.0 Actuator git 属性未添加到 /info

Spring Boot 2.0 整合Thymeleaf 模板引擎

Spring Boot 2.0:Docker Compose + Spring Boot +

Spring Boot Actuator 2.0 使用

Spring boot 2.0 - 为用户配置