SpringBoot使用FastJson,并解决中文乱码的问题

Springboot使用FastJson后,接口返回中文乱码的问题解决(两种解决方式)

方法一

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

import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

@Configuration
public class MySpringMvcConfig extends WebMvcConfigurerAdapter{
    
    /**
     * 消息转换器
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //1.定义converter消息转换对象
        FastJsonHttpMessageConverter fastconverter = new FastJsonHttpMessageConverter();
        
        //2.添加fastJson配置信息,比如:是否格式化返回的json数据
        FastJsonConfig fastJsonconfig = new FastJsonConfig();
        fastJsonconfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        
        //3.解决乱码问题。定义响应的MIME类型,设置响应的content-type为application/json;charset=UTF-8
        List<MediaType> fastMediaType = new ArrayList<>();
        fastMediaType.add(MediaType.APPLICATION_JSON_UTF8);
        
        //4.converter消息转换器添加配置信息
        fastconverter.setSupportedMediaTypes(fastMediaType);
        fastconverter.setFastJsonConfig(fastJsonconfig);
        converters.add(fastconverter);
    }
    
}

方法二

在具体的方法上添加“produces = MediaType.APPLICATION_JSON_UTF8_VALUE”

@GetMapping(value = Url.XXX, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)

 

参考文献:https://blog.csdn.net/qq_38288606/article/details/78673336

posted @ 2020-03-18 21:19  圣痕道心  阅读(1194)  评论(0编辑  收藏  举报