package cn.hncu.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.hncu.domain.User; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class JsonServlet2 extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); List<User> users = new ArrayList<User>(); users.add(new User("A001","Jack",20)); users.add(new User("A002","Rose",22)); users.add(new User("B001","张三",20)); users.add(new User("B002","李四",30)); String strJson=com.alibaba.fastjson.JSONArray.toJSONString(users); System.out.println(strJson); //用fastjson工具(只有一个jar包)帮我们把list转换成json串 Map<String, Object> map = new HashMap<String, Object>(); map.put("addr", "湖南"); map.put("height", "170"); map.put("marry", "no"); map.put("user", new User("A003","小李",25)); String strMap=com.alibaba.fastjson.JSONArray.toJSONString(map); out.print(strMap.toString()); } }
JsonServlet3.java
package cn.hncu.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import cn.hncu.domain.User; public class JsonServlet3 extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); List<User> users = new ArrayList<User>(); users.add(new User("A001","Jack",20)); users.add(new User("A002","Rose",22)); users.add(new User("B001","张三",20)); users.add(new User("B002","李四",30)); //用fastjson工具(只有一个jar包)帮我们把list转换成json串 JSONArray json=JSONArray.fromObject(users); String strJson=json.toString(); System.out.println(strJson); Map<String, Object> map = new HashMap<String, Object>(); map.put("addr", "湖南"); map.put("height", "170"); map.put("marry", "no"); map.put("user", new User("A003","小李",25)); JSONObject obj = JSONObject.fromObject(map); System.out.println(obj.toString()); out.print(obj.toString()); } }