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数据中文乱码问题解决

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值