Kim*_*Kim 3 java json jsp servlets gson
如果我有这样的表:
MsUser
- userID
- username
MsProject
- userID
- ProjectID
- ProjectName
Run Code Online (Sandbox Code Playgroud)
如果我有这样的查询:
Result set = select * from MsUser mu, MsProject mp WHERE mu.userID = mp.userID
Run Code Online (Sandbox Code Playgroud)
我可以使用将结果集从上述查询转换为JSON Google gson吗?顺便说一句,我使用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;
}
Run Code Online (Sandbox Code Playgroud)
如果您想将此jsonArray转换为json对象,请使用以下方法,
JSONObject jsonObject = new JSONObject();
jsonObject.put("arrayName",jsonArray);
Run Code Online (Sandbox Code Playgroud)
更新:要在json对象中转换ResultSet,我们需要使用org.json jar。您应该下载并添加到您的项目类路径中。
| 归档时间: |
|
| 查看次数: |
7407 次 |
| 最近记录: |