servlet中的代码,需要用到fastjson库
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//组装数据
Map map=new HashMap();
map.put("code", 1);
map.put("name", "小明");
map.put("age", 22);
map.put("性别", "男");
String str=JSON.toJSONString(map);//调用fastjson将map转换为json字符串
resp.setContentType( "text/html;charset=UTF-8 ");//设置编码集,否则中文会发生乱码
PrintWriter pw=resp.getWriter();
pw.println(str);//输出该json字符串
pw.flush();//清空缓冲区,立即输出
}