1
在我的Web服務中,我正在查詢數據庫,並且想返回2列數據庫並將這些列放入2d數組中。多維數組到JSON java/android gson
另外我想將數組轉換爲JSON併發送給客戶端。使用gson的客戶端在2d數組中解析來自服務器的消息。可能嗎?
我已經嘗試了很多,但至今沒有運氣。先謝謝你。
的最後一個版本我試過是這樣的:
private static String[][] db_load_mes (String u){
ArrayList<String> array1 = new ArrayList<String>();
ArrayList<String> array2 = new ArrayList<String>();
JSONObject messages = new JSONObject();
Connection c = null;
try{
// Load the driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
c = DriverManager.getConnection("jdbc:odbc:dsn1","mymsg","mymsg");
Statement s = c.createStatement();
// SQL code:
ResultSet r;
r = s.executeQuery("select * from accounts ");
int i = 0, j = 0;
int k = 0;
String x,y;
while(r.next()) {
x = r.getString("username");
array1.add(x);
y = r.getString("password");
array2.add(y);
k = k + 1;
}
int count = array1.size();
String[][] row = new String[count][2];
Iterator<String> iter = array1.iterator();
while (iter.hasNext()) {
row[i][0]=iter.next();
i++;
}
Iterator<String> iter2 = array2.iterator();
while (iter2.hasNext()) {
row[j][1]=iter2.next();
j++;
}
for(int z=0;z<count;z++)
System.out.println(row[z][0] + "\t" + row[z][1] + "\n");
if (k == 0)
System.err.println("no accounts!");
c.close();
s.close();
}
catch(SQLException se)
{
System.err.println(se);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return ...;
}
與上面的代碼我可以創建二維數組,但我怎麼能發送此陣給客戶端。
甩掉數據庫我最後一次測試使用arrayList,但它沒有工作。如何將數據庫的兩列放入二維數組中。我不知道如何在JSON中轉換多維數組。 – anna
告訴我們你已經嘗試過了。 [問] – Jack
我基於這個http://stackoverflow.com/questions/5010930/convert-sql-query-result-into-array-of-strings/5010967#5010967。 – anna