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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM