如果我有这样的表:
MsUser
- userID
- username
MsProject
- userID
- ProjectID
- ProjectName
如果我有这样的查询:
Result set = select * from MsUser mu, MsProject mp WHERE mu.userID = mp.userID
我可以使用Google gson
将上面查询的结果集转换为JSON吗?
顺便说一句,我使用JSP来开发我的应用程序。
答案 0 :(得分:4)
您可以使用此方法将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应该下载并添加到项目类路径中。