1. 程式人生 > >使用ajax請求 返回Json出現亂碼解決方法

使用ajax請求 返回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));
    }