结果集使用gson 到json
如果我有这样的表:
MsUser - userID - username MsProject - userID - ProjectID - ProjectName
如果我有这样的查询:
Result set = select * from MsUser mu, MsProject mp WHERE mu.userID = mp.userID
我可以使用Google gson
将结果集从上面的查询转换为JSON吗? 顺便说一句,我使用JSP来开发我的应用程序。
您可以使用此方法将ResultSet
对象转换为jsonArray
。
public static JSONArray convertToJSON(ResultSet resultSet) throws Exception { JSONArray jsonArray = new JSONArray(); while (resultSet.next()) { int total_columns = resultSet.getMetaData().getColumnCount(); JSONObject obj = new JSONObject(); for (int i = 0; i < total_columns; i++) { obj.put(resultSet.getMetaData().getColumnLabel(i + 1).toLowerCase(), resultSet.getObject(i + 1)); } jsonArray.put(obj); } return jsonArray; }
如果你想将这个jsonArray转换为json对象,那么使用下面的方法,
JSONObject jsonObject = new JSONObject(); jsonObject.put("arrayName",jsonArray);
更新:要在json对象中转换ResultSet,我们需要使用org.json jar.you应该下载并添加到项目类路径中。