正如標題,我有我的JSON格式字符串爲數組的數組(列表)的問題JSON陣列格式問題
基本上這就是我想的格式見:
{"Item":
["Id: 1","Title: Surface Pro 4","Phone: 4077603835","Email:
[email protected]","Description: Surface Pro 4 for sale, in
excellent condition, basically brand new!"],
"Item":
"Id: 2","Title: Macbook Air","Phone: null","Email:
null","Description: null"],
"Item":
"Id: 3","Title: Lenovo Laptop","Phone: 3433215565","Email:
XXXXXXXX.com","Description: Free Macbook Air, I promise"]
}
然而,這是下面的格式,我的代碼是生產:
{"Item":["Id: 1","Title: Surface Pro 4","Phone: 4077603835","Email:
[email protected]","Description: Surface Pro 4 for sale, in
excellent condition, basically brand new!","Id: 2","Title: Macbook
Air","Phone: null","Email: null","Description: null","Id: 3","Title:
Lenovo Laptop","Phone: 3433215565","Email:
XXXXXXXX.com","Description: Free Macbook Air, I promise"]}
我只是想看看不同的數組中的每個項目!我認爲問題在於這部分代碼:「obj.put(」Item「,items);」因爲它將所有項目放在同一個數組中,但我如何動態創建不同的數組?我的物品清單將不斷擴大,永遠不會保持不變。
代碼:
public List<String[]> SelectAllSQL() {
List<String[]> result = new ArrayList<String[]>();
sql = "select * from item";
try {
ResultSet rs = stmt.executeQuery(sql);
rs.last();
int lastRow = rs.getRow();
for(int row = 1; row <= lastRow; row++) {
rs.absolute(row);
result.add(new String[] {rs.getString("title"),
rs.getString("phone"), rs.getString("email"),
rs.getString("description"),
rs.getString("id")});
}
return result;
}
catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public String getIt() {
ConnectionDB db = new ConnectionDB();
QueryDB query = new QueryDB();
List<String[]> sqlResult = new ArrayList<String[]>();
db.Connect();
sqlResult = query.SelectAllSQL();
JSONObject obj = new JSONObject();
JSONArray items = new JSONArray();
for(String[] arr : sqlResult) {
items.add("Id: " + arr[4]);
items.add("Title: " + arr[0]);
items.add("Phone: " + arr[1]);
items.add("Email: " + arr[2]);
items.add("Description: " + arr[3]);
obj.put("Item", items);
}
return obj.toJSONString();
將'JSONArray items = new JSONArray();'放入'for'循環的範圍中。在你的情況下,你對所有不同的項目使用相同的「項目」。 – David