您的当前位置:首页正文

Springboot使用FastJson返回中文乱码的解决方案

2024-11-10 来源:个人技术集锦

两种方法:

	/**
	 * 重写configureMessageConverters方法
	 */
	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		super.configureMessageConverters(converters);
		/*
		 * 1、需要先定义一个 convert 转换消息的对象;
		 * 2、添加fastJson 的配置信息,比如:是否要格式化返回的json数据;
		 * 3、在convert中添加配置信息.
		 * 4、将convert添加到converters当中.
		 * 
		 */
		// 1、需要先定义一个 convert 转换消息的对象;
		FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
		
		//2、添加fastJson 的配置信息,比如:是否要格式化返回的json数据;
		FastJsonConfig fastJsonConfig = new FastJsonConfig();
		fastJsonConfig.setSerializerFeatures(
                SerializerFeature.PrettyFormat
        );
        
		 //解决中文乱码问题:在方法内部添加这段代码
		List<MediaType> fastMediaTypes = new ArrayList<>();
		fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
		fastConverter.setSupportedMediaTypes(fastMediaTypes);
		
		//3、在convert中添加配置信息.
        fastConverter.setFastJsonConfig(fastJsonConfig);
        //4、将convert添加到converters当中.
    	converters.add(fastConverter);
	}

二、在controller上的@ReqRequestMapping注解上添加produces = "application/json; charset=utf-8"

@RequestMapping(value="/getDemo",produces = "application/json; charset=utf-8")
  public Demo getDemo(){
     Demo demo = new Demo();
     demo.setId(1);
     demo.setName("张三");
     demo.setCreateTime(new Date());
     return demo;

  }

本文如未解决您的问题请添加抖音号:51dongshi(抖音搜索懂视),直接咨询即可。

热门图文

Top