标签:style blog http color io os ar java for
分类: Web JAVA2013-09-17 14:38 4805人阅读 评论(1) 收藏 举报
在Servlet中覆写doGet方法,是用JSONStringer 类:
[java] view plaincopyprint?
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类, 则如下:
[java] view plaincopyprint?
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");
标签:style blog http color io os ar java for
原文地址:http://my.oschina.net/u/1049180/blog/335787