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

Posted 圣痕道心

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

以上是关于SpringBoot使用FastJson,并解决中文乱码的问题的主要内容,如果未能解决你的问题,请参考以下文章

springboot使用FastJson返回Json视图

Fastjson @JsonField 不起作用

springboot使用阿里fastjson来解析数据

SpringBoot入门笔记使用fastjson

springBoot系列教程05:fastjson的集成配置及使用

SpringBoot中读取JSON文件信息并转换为Map对象