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


 

問題:

后台代碼如下:

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

前台代碼如下:

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

發現前台顯示的json數據中的中文為???。亂碼問題。

原因:

Spring中解析字符串的轉換器默認編碼居然是ISO-8859-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();
    }

方法二:在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;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM