springmvc返回json字符串中文亂碼問題

 

問題:html

後臺代碼以下:web

    @RequestMapping("menuTreeAjax")
    @ResponseBody
    /**
     * 根據parentMenuId獲取菜單的樹結構
     * @param parentMenuId
     * @return
     */
    public String menuTreeAjax(Integer parentMenuId) {
        JSONArray array = menuService.getTreeMenuByParentMenuId(parentMenuId);
        return array.toString();
    }

前臺代碼以下:ajax

    $.ajax({
            url:'menuTreeAjax?parentMenuId=${menu.menuId}',
            async:false,
            dataType:"json",
            success:function(data){
                menuTree=data;
                alert(data[0].text);
            }
        });

發現前臺顯示的json數據中的中文爲???。亂碼問題。spring

緣由:json

Spring中解析字符串的轉換器默認編碼竟然是ISO-8859-1mvc

以下所示:app

解決方法:async

方法一,使用(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();
    }

方法二:在springmvc.xml配置:url

  <!-- 處理請求返回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;
    }
相關文章
相關標籤/搜索