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

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

 

解决方式1:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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:

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

  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值