SSM后端返回json数据,JSON中文乱码解决办法


解决方法一

在 controller 中的每个方法的 @RequestMappering 注解中进行编码设置:

@RequestMapping(value = "/query",produces = "text/plain;charset=utf-8")
@ResponseBody

解决方法二

在spring-mvc.xml中 配置,添加如配置。


    <mvc:annotation-driven >
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter" >
                <property name = "supportedMediaTypes">
                    <list>
                        <value>application/json;charset=utf-8value>
                        <value>text/html;charset=utf-8value>
                        
                        <value>application/x-www-form-urlencodedvalue>
                    list>
                property>
            bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" >bean>
        mvc:message-converters>
    mvc:annotation-driven>

解决方法三

直接实现WebMvcConfigurer,并重写 configureMessageConverters()方法。。

/**
* 消息内容转换配置
 * 配置fastJson返回json转换
 * @param converters
 */
@Override
public void configureMessageConverters(List> converters) {
    //调用父类的配置
    super.configureMessageConverters(converters);
    //创建fastJson消息转换器
    FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
    //创建配置类
    FastJsonConfig fastJsonConfig = new FastJsonConfig();
    //修改配置返回内容的过滤
    fastJsonConfig.setSerializerFeatures(
            SerializerFeature.DisableCircularReferenceDetect,
            SerializerFeature.WriteMapNullValue,
            SerializerFeature.WriteNullStringAsEmpty
    );
    fastConverter.setFastJsonConfig(fastJsonConfig);
    //将fastjson添加到视图消息转换器列表内
    converters.add(fastConverter);

}