首先在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