gpt4 book ai didi

java - 将结果集放入java中的数组中

转载 作者:太空宇宙 更新时间:2023-11-04 10:36:00 25 4
gpt4 key购买 nike

我在 java 中使用 select2,我需要将 resultset 放入名为 resutls 的数组中。

这是我的代码:

java

public static String convertResultSetToJson(ResultSet resultSet) throws SQLException {
JSONArray json = new JSONArray();
ResultSetMetaData metadata = resultSet.getMetaData();
int numColumns = metadata.getColumnCount();

//iterate rows
while (resultSet.next()) {
JSONObject obj = new JSONObject(); //extends HashMap
//iterate columns
for (int i = 1; i <= numColumns; ++i) {
String column_name = metadata.getColumnName(i);
obj.put(column_name, resultSet.getObject(column_name).toString());
}
json.add(obj);
}

return json.toJSONString();
}

我这样调用它:

ResultSet list = connection.executeWithResult("select * from test where id::text like '%" + term + "%'");
out.print(functions.convertResultSetToJson(list));

输出:

[{date: "1996-12-11", systemId: "3", creator: "3", boss: "3", creatorChart: "1", subSystemId: "4",…}]

我的问题是,如何产生这样的输出?

 {results:[date: "1996-12-11", systemId: "3", creator: "3", boss: "3", creatorChart: "1", subSystemId: "4",…]}

最佳答案

您当前的输出是有效的 JSON。这是一个对象数组。

[{
date: "1996-12-11",
systemId: "3",
creator: "3",
boss: "3",
creatorChart: "1",
subSystemId: "4"
}]

但是您想要实现的并不是有效的 JSON。

{results:[date: "1996-12-11", systemId: "3", creator: "3", boss: "3", creatorChart: "1", subSystemId: "4",…]}

正如 @Harald 在评论中提到的,如果你想将数组包装在包装对象中,那么你可以这样做

public static String convertResultSetToJson(ResultSet resultSet) throws SQLException {
JSONArray json = new JSONArray();
ResultSetMetaData metadata = resultSet.getMetaData();
int numColumns = metadata.getColumnCount();

//iterate rows
while (resultSet.next()) {
JSONObject obj = new JSONObject(); //extends HashMap
//iterate columns
for (int i = 1; i <= numColumns; ++i) {
String column_name = metadata.getColumnName(i);
obj.put(column_name, resultSet.getObject(column_name).toString());
}
json.add(obj);
}
JSONObject resultsObject = new JSONObject();
resultsObject.put('results', json);
return resultsObject.toJSONString();
}

这将生成以下 JSON。

{
results: [{
date: "1996-12-11",
systemId: "3",
creator: "3",
boss: "3",
creatorChart: "1",
subSystemId: "4"
}]
}

关于java - 将结果集放入java中的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49473228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com