多维数组到JSON java/android gson
问题描述:
在我的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 ...;
}
与上面的代码我可以创建二维数组,但我怎么能发送此阵给客户端。
答
下面是我如何使用Gson从谷歌... 下载gson from here 将它包括在您的项目中。
package javaapplication1;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JavaApplication1 {
public static void main(String[] args) {
int rows = 3;
String records[][] = new String[][]{{"bob", "123-pass"},
{"erika", "abc123"},
{"richard", "123123123"}
};
Gson gson = new Gson();
String recordsSerialized = gson.toJson(records);
System.out.println(recordsSerialized);
/* prints this
[["bob","123-pass"],["erika","abc123"],["richard","123123123"]]
*/
// if you want a better output import com.google.gson.GsonBuilder;
Gson gsonPretty = new GsonBuilder().setPrettyPrinting().create();
String recordsSerializedPretty = gsonPretty.toJson(records);
System.out.println(recordsSerializedPretty);
/* PRINTS IN different lines.. I can't paste it here */
// for retrieval
String retrievedArray[][] = gsonPretty.fromJson(recordsSerializedPretty, String[][].class);
for (int i = 0; i < retrievedArray.length; i++) {
for (int j = 0; j < retrievedArray[0].length; j++) {
System.out.print(retrievedArray[i][j]+" ");
}
System.out.println("");
}
// PRINTS THIS
/*
bob 123-pass
erika abc123
richard 123123123
*/
}
}
甩掉数据库我最后一次测试使用arrayList,但它没有工作。如何将数据库的两列放入二维数组中。我不知道如何在JSON中转换多维数组。 – anna
告诉我们你已经尝试过了。 [问] – Jack
我基于这个http://stackoverflow.com/questions/5010930/convert-sql-query-result-into-array-of-strings/5010967#5010967。 – anna