import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject;
result转JSON字符
public String resultSetToJson(ResultSet rs) throws SQLException, JSONException { // json数组 JSONArray array = new JSONArray(); int rCount=0; // 获取列数 ResultSetMetaData metaData = rs.getMetaData(); int columnCount = metaData.getColumnCount(); // 遍历ResultSet中的每条数据 while (rs.next()) { JSONObject jsonObj = new JSONObject(); // 遍历每一列 for (int i = 1; i <= columnCount; i++) { String columnName =metaData.getColumnLabel(i).trim(); String value = ""; if (!"".equals(rs.getString(columnName))) { value =rs.getString(columnName).trim(); } jsonObj.put(columnName, value); } array.add(jsonObj); rCount++; } JSONObject reJson = new JSONObject(); reJson.put("status", "success"); reJson.put("totals", rCount); reJson.put("data", array); return reJson.toString(); }
JSON字符串转换(JSP):
<% String url="http://localhost:8080/dfcwfz_war_exploded/SQLtoJSON?SQL=U0VMRUNUIMDg0M0sz+7Ev7HgusUsz+7Ev8P7s8YsuLrU8MjLLMTqtsgsxr7WpLrFLL/GxL+0+sLrIEZST00gytXWp8P3z7g="; BufferedReader br = new BufferedReader(new InputStreamReader(new URL(url).openConnection().getInputStream(),"UTF-8")); StringBuffer str = new StringBuffer(); String realLineStr = null; while((realLineStr = br.readLine()) != null){ str.append(realLineStr).append("\r\n"); //每读取一行就换行 } JSONObject tJson =JSON.parseObject(str.toString()); JSONArray JsonDATA = tJson.getJSONArray("data"); String reStr=""; for(int i=0;i<JsonDATA.size();i++) { reStr+="<li>项目名称:"+JsonDATA.getJSONObject(i).get("项目名称")+"</li>"; reStr+="<li>科目代码:"+JsonDATA.getJSONObject(i).get("科目代码")+"</li>"; } %> <li>status=<%=tJson.getString("status")%></li> <li>totals=<%=tJson.getDouble("totals")%></li> <%=reStr%>
发表评论