我正在使用带有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",…]}
答案 0 :(得分:0)
您当前的输出是有效的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"
}]
}