如何将servlet中读取的数据转化为JSON

首先在JDBC的DAO中读取的数据要是 List<Map<String, Object>>类型

public static List<Map<String, Object>> selectProvince() {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "SELECT * FROM city where iscity=? ORDER BY namesort";
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			con = (Connection) jdbc.getcon();
			ps = con.prepareStatement(sql);
			ps.setInt(1, 0);
			rs = ps.executeQuery();
			while (rs.next()) {
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("city_name", rs.getString("city_name"));
				map.put("city_traver_num", rs.getInt("city_traver_num"));
				map.put("iscity", rs.getInt("iscity"));
				map.put("city_category", rs.getInt("city_category"));
				map.put("namesort", rs.getString("namesort"));
				map.put("city_id", rs.getInt("city_id"));
				list.add(map);
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			jdbc.free(rs, ps, con);
		}
		return list;
	}

然后在Servlet中遍历时,进行转换:

public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("gb2312");
		response.setCharacterEncoding("gb2312");
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		CityDao dao = new CityDao();
		List<Map<String, Object>> citys = dao.selectProvince();
		if (citys == null) {
			out.print("error");
		} else {
			JSONStringer stringer = new JSONStringer();
			stringer.array();
			for (int i = 0; i < citys.size(); i++) {
				Map<String, Object> city= citys.get(i);
				try {
					stringer.object();
					Iterator it = city.keySet().iterator();
					while (it.hasNext()) {
						Object key = it.next();
						stringer.key((String) key).value(city.get(key));
					}
					stringer.endObject();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			stringer.endArray();			
			out.print(stringer.toString());
		}
		out.flush();
		out.close();

	}
}
此时,输出的数据就变为JSON类型了

注意:由于使用了JSONStringer所以必须引入JAR包,共要引入四个json-lib-2.4-jdk15.jar   ezmorph-1.0.3.jar  commons-lang-2.3.jar  commons-beanutils-1.7.0.jar


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值