方式一
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);
}
方式三
这是方式二的简化.
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);
}