java后台响应数据的方式

2018-01-09  本文已影响0人  Nisus_Liu

方式一


 public void test() throws IOException {

        JSONObject o = new JSONObject();
        o.put("name", "zhangfei");
        ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
        ServletActionContext.getResponse().getWriter().write(o.toString());

    }

方式二

 public void test() throws IOException {

        String s = "{'name':'zhangfei'}";
        // 必须这么转一下, 否则前台报 Json.parse错误
        String json = JSONObject.fromObject(s).toString();
        ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
        ServletActionContext.getResponse().getWriter().write(json);

    }

image.png

方式三

这是方式二的简化.

 public void test() throws IOException {

        String s = "{\"name\":\"zhangfei\"}";
        // 由于将单引号改成了双引号(加转义符号), 就不
//        String json = JSONObject.fromObject(s).toString();
        ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
        ServletActionContext.getResponse().getWriter().write(s);

    }
上一篇下一篇

猜你喜欢

热点阅读