Java Servlet生成Json格式数据

3 篇文章 0 订阅

在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将数据写入返回










  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值