美文网首页
java后台响应数据的方式

java后台响应数据的方式

作者: Nisus_Liu | 来源:发表于2018-01-09 02:49 被阅读0次

方式一


 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);

    }

相关文章

网友评论

      本文标题:java后台响应数据的方式

      本文链接:https://www.haomeiwen.com/subject/qvainxtx.html