Bootstrap

json在后台封装后,返回中文乱码

Spring版本:3.*RELEASE

这里统一转换为utf-8
因为低版本的spring缺少许多方法,所以不能用produces

方案一、将json数据写入PrintWriter 流中
@RequestMapping(value="/upload")
    public  void upload( HttpServletResponse response) throws Exception{

            //创建Json对象
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msg","hello");
            jsonObject.put("msg2","world");
            try {
           response.setContentType("text/html;charset=utf-8");         
            PrintWriter out = response.getWriter(); //获取写入对象  
            out.print(json); //将json数据写入流中  
            out.flush();  
            out.close();
              } catch (IOException e) {
                 e.printStackTrace();
            } //获取写入对象 

    }
方案二、将json数据写入ServletOutputStream 流中
@RequestMapping(value="/upload")
    public  void upload(@RequestParam("file") MultipartFile file,HttpServletRequest request, HttpServletResponse response) throws Exception{
         //创建Json对象
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msg","hello");
            jsonObject.put("msg2","world");
            try {

            //要将json对象转换为string类型
                String json = jsonObject.toString();
                 ServletOutputStream os = response.getOutputStream(); //获取输出流  
                 os.write((json.getBytes(Charset.forName("utf-8")))); //将json数据写入流中  
                 os.flush(); 
                 os.close();    
            } catch (IOException e) {
                 e.printStackTrace();
            } //获取写入对象 

    }
更高版本的spring可以利用设置 @RequestMapping 的 produces 参数
@RequestMapping(value="/upload",produces = "text/html;charset=UTF-8")
@ResponseBody 
    public  jsonObject upload(@RequestParam("file") MultipartFile file,HttpServletRequest request, HttpServletResponse response) throws Exception{
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");

            //创建Json对象
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msg","hello");
            jsonObject.put("msg2","world");
            return jsonObject ;

    }

[参考链接]:Spring MVC3返回JSON数据中文乱码问题解决

;