html json中文乱码,Spring boot 解决后台返回 json 到前台出现中文乱码的问题

spring boot 解决后台返回 json 到前台出现中文乱码的问题。

这个一般是老版本项目可能会出现这个问题,新版本只要按照标准来,一般不会出现。

如果出现了,应该怎么解决呢,一般两种方案,方案如下:

第一种:在Controller 中@RequestMapping中添加注解 produces="application/json;charset=UTF-8"

@RequestMapping(value = "/user/list", method=RequestMethod.POST, produces="application/json;charset=UTF-8")

这个方法的弊端就是每个方法都需要加。

第二种:修改配置类:

import java.nio.charset.Charset;

import java.util.List;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;

import org.springframework.http.converter.HttpMessageConverter;

import org.springframework.http.converter.StringHttpMessageConverter;

import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration

@EnableWebMvc

@ComponentScan

public class MvcConfiguration extends WebMvcConfigurerAdapter {

@Bean

public HttpMessageConverter responseBodyConverter() {

StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));

return converter;

}

@Override

public void configureMessageConverters(List> converters) {

super.configureMessageConverters(converters);

converters.add(responseBodyConverter());

}

}

新版本,有的类已经过时,可能需要改成如下代码:

@Configuration

public class WebMvcConfig extends WebMvcConfigurationSupport {

@Override

protected void extendMessageConverters(List> converters) {

// 解决controller返回字符串中文乱码问题

for (HttpMessageConverter> converter : converters) {

if (converter instanceof StringHttpMessageConverter) {

((StringHttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);

} else if (converter instanceof MappingJackson2HttpMessageConverter) {

((MappingJackson2HttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);

}

}

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值