2017-04-05 108 views
0

內部數組這是在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

回答

0

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

是確切的輸出來了 謝謝德林先生在編碼方面的幫助.... –