这是JAVA中的代码,我使用了JSONArray和方法JSONarray.put(string);
public JSONArray getChart() {
Connection con = getConnectionObject();
Statement st = null;
ResultSet rs = null;
JSONObject jCharto = new JSONObject();
JSONArray arr = new JSONArray();
try {
st = con.createStatement();
String query = "select count(books_issued) as books_issued,command from fact_aaglib, school where fact_aaglib.school_name = school.school_name group by command;";
rs = st.executeQuery(query);
System.out.println("['Command','Book Issued'],");
while (rs.next())
{
String zone = rs.getString("command");
arr.put(zone);
int booksissued = rs.getInt("books_issued");
arr.put(booksissued);
}
System.out.println(arr+",");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (con != null)
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return arr;
}
这是我的输出
['Command','Book Issued'],["Central",324,"Southern",312,"South-West",192,"Eastern",264,"Northern",84,"Western",396],
但实际上我想要这样的输出:
[
['Command', 'Books Issued'],
["Central",324],["Southern",312],
["South-West",192],
["Eastern",264],
["Northern",84],
["Western",396]
]
此数据用于在谷歌图表中绘制条形图。
答案 0 :(得分:0)
JSONArray
不限于字符串。
您需要创建一个用于保存记录的数组,然后为每对或多个记录创建一个新数组。这是基本的想法:
// create the "top" array
JSONArray topArray = new JSONArray();
// add your static "headers"
JSONArray headers = new JSONArray();
headers.put("Command");
headers.put("Book Issued");
topArray.put(headers);
while (rs.next()){
// create a new array for the current record
JSONArray recordArray = new JSONArray();
// populate the record array
String zone = rs.getString("command");
recordArray.put(zone);
int booksissued = rs.getInt("books_issued");
recordArray.put(booksissued);
// append the record array to the top array
topArray.put(recordArray);
}
return topArray;