springmvc返回json字符串中文乱码问题

本文介绍了解决SpringMVC框架中JSON响应乱码的两种方法:一是通过@RequestMapping注解指定字符集;二是配置SpringMVC的message-converters来统一处理字符集。此外,还提供了一个处理字符串响应的例子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、方法一(推荐),使用(produces = "application/json; charset=utf-8")

@RequestMapping(value="menuTreeAjax", produces = "application/json; charset=utf-8")
    @ResponseBody
    /**
     * 根据parentMenuId获取菜单的树结构
     * @param parentMenuId
     * @return
     */
    public String menuTreeAjax(Integer parentMenuId) {
        JSONArray array = menuService.getTreeMenuByParentMenuId(parentMenuId);
        return array.toString();
    }

2、方法二:在springmvc.xml配置:

<!-- 处理请求返回json字符串的乱码问题 -->  
     <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

 PS:如果返回的不是json,而只是一个字符串,则只需要这样就可以了。将produces改为text/html

@ResponseBody
    @RequestMapping(value="webserviceDemo1", produces = "text/html; charset=utf-8")
    public String webserviceDemo1(){
        WeatherServiceService factory=new WeatherServiceService();
        WeatherService service=factory.getWeatherServicePort();
        String result=service.getWeatherByCityname("厦门");
        return result;
    }

感谢https://www.cnblogs.com/roy-blog/p/7048401.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值