zoukankan      html  css  js  c++  java
  • FastJson中文乱码

    初学springboot使用fastJson替换默认的jackson后出现中文乱码

    解决方式1:

    import java.util.ArrayList;
    import java.util.List;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    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;
    
    @SpringBootApplication  // 继承 WebMvcConfigurerAdapter   用于将fastjson替换原有的jackson
    public class MainApplication extends WebMvcConfigurerAdapter  {
        // 配置fastJson  用于替代jackson
        @Override
        public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
            super.configureMessageConverters(converters);
            //定义一个convert 转换消息的对象
            FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
            // 2 添加fastjson 的配置信息 比如 是否要格式化 返回的json数据
            FastJsonConfig fastJsonConfig = new FastJsonConfig();
            fastJsonConfig.setSerializerFeatures(
                    SerializerFeature.PrettyFormat
            );
            fastConverter.setFastJsonConfig(fastJsonConfig);
            // 解决乱码的问题
            List<MediaType> fastMediaTypes = new ArrayList<>();
            fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
            fastConverter.setSupportedMediaTypes(fastMediaTypes);
            converters.add(fastConverter);
        }
    
       public static void main( String[] args )   {
            SpringApplication.run(MainApplication.class, args);
       }
    }
    
    
    

      

    解决方式2:

    在controller 的方法中 地址映射加入指定编码格式 这个时候也中文不乱码了
    @RequestMapping(value = "/", produces = "application/json; charset=utf-8")
    

      

  • 相关阅读:
    SecureCRT上传文件到服务器 CentOS举例
    MongoDB关于replSet的配置概述(一主二从)
    MongoDB的安装与卸载与再安装……
    zip在python中的使用方法
    try,raise等的python的使用方法介绍
    【转】jQuery给动态添加的元素绑定事件的方法
    sublime的纵向操作(列操作)原来这么用
    Python 利用*args和**kwargs解决函数遇到不确定数量参数问题
    Python 函数式编程介绍
    Python list可以做什么
  • 原文地址:https://www.cnblogs.com/achengmu/p/9294837.html
Copyright © 2011-2022 走看看