阵列使用JSON

问题描述:

内部数组这是在Java代码中我用JSONArray和方法JSONarray.put(string);阵列使用JSON

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

'Javascript' ='Java' – Weedoze

A 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; 
+0

谢谢缩醛树脂先生快速回复... **实际输出的未来是这样的:!** '[”中央“,324], [”Southern“,312], [”South-West“,192], [”Eastern“,264], [”Northern“,84], [”Western“ 396]' **我想这样的输出:** '[ \t [ '命令', '发行书籍'] \t [ “中央”,324], \t [ “南”,312], \t [ “西南”,192], \t [ “东”,264], \t [ “北”,84 ], \t [ “西”,396] \t]' 谢谢 –

+0

如果只是第一阵列丢失,'while'(见更新答案)前加入。 (顺便说一句,这是错误的Derlin ^^) – Derlin

+0

是确切的输出来了 谢谢德林先生在编码方面的帮助.... –