Java Servlet生成Json格式数据

在Servlet中覆写doGet方法,是用JSONStringer 类:

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
	// TODO Auto-generated method stub
	String IdList = Dao.getAllTourId();
	String[] strID = IdList.split("#");
	
	JSONStringer stringer = new JSONStringer();
	int tID;
	String tourName, tourList, tourIdList;

	try {
		stringer.array();
		for(int i = 0; i < strID.length; i++) {
			tID = Integer.parseInt(strID[i]);
			tourName = Dao.getTourName(tID);
			tourList = Dao.getTourList(tID);
			tourIdList = Dao.getPlaceIdList(tID);
			stringer.object().key("tID").value(tID).
				key("name").value(tourName).
				key("tourList").value(tourList).
				key("tourIDList").value(tourIdList).endObject();
		}
		stringer.endArray();
	} catch (JSONException e) {
		e.printStackTrace();
	} catch (Exception e) {
		e.printStackTrace();
	}
	resp.getOutputStream().write(stringer.toString().getBytes("UTF-8"));
	resp.setContentType("text/json; charset=UTF-8");
}

如果其中是用了HashMap类, 则如下:

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
	// TODO Auto-generated method stub
	
	String param = req.getParameter("param");
	TourManager tm = new TourManager();
	JSONStringer stringer = new JSONStringer();
	
	if(param.equals("Place")) {
		HashMap mapPlace = tm.getPlace();
		
		try {
			stringer.array();
			
			stringer.object();
			Iterator it = mapPlace.keySet().iterator();
			while(it.hasNext()) {
				Object key = it.next();
				stringer.key((String)key).value(mapPlace.get(key));
			}
			stringer.endObject();
			
			stringer.endArray();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	else if(param.equals("Tour")) {
		HashMap mapTour = tm.getTours();
		
		try {
			stringer.array();
			
			stringer.object();
			Iterator it = mapTour.keySet().iterator();
			while(it.hasNext()) {
				Object key = it.next();
				stringer.key((String)key).value(mapTour.get(key));
			}
			stringer.endObject();
			stringer.endArray();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	resp.getOutputStream().write(stringer.toString().getBytes("UTF-8"));
	resp.setContentType("text/json; charset=UTF-8");

最后是用resp将数据写入返回










你可能感兴趣的:(JAVA,Web)