使用ajax請求SpringMVC返回Json出現亂碼解決方法


1:在使用ajax請求后台訪問數據的數據,后台返回的數據是亂碼,帶??問號的亂碼,之前還一直沒有遇到過,在這里記錄整理一下,貼出解決代碼! 
(1):前台使用ajax ,已經設定返回的結果為json格式!ajax代碼不貼出來了! 
(2):后台代碼

@RequestMapping(value = { "/hello/{uuid}" }, method = RequestMethod.GET /*,produces = "text/html;charset=UTF-8"*/)
    @ResponseBody
    public String hello(@PathVariable("uuid") String uuid) {
        String result = "";

        //do something  
        //使用Json返回json格式數據

        return JSON.toJSONString(result);;
    }

在沒有加produces = “text/html;charset=UTF-8” 之前,返回的結果一直是亂碼,很奇怪,項目中web.xml也設置了編碼格式utf-8 ,沒有找到最終的原因,不過找到了這種解決方法!

2:如果上面的方法還是不能解決的話就用下面的方法:

@ResponseBody
    public void hello(@PathVariable("uuid") String uuid,HttpServletResponse response) {
        String result = "";

        //do something  
        //使用Json返回json格式數據
        JSONObject josn = new JSONObject();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().print(JSON.toJSON(result));
    }

 


免責聲明!

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



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