As the title suggests, I'm having an issue with my JSON formatting for an Array of String Arrays (List)
Basically, this is the format that I would like to see:
{"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"]
}
However, this is the below format that my code is producing:
{"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"]}
I just want to see separate arrays for each item! I think the issue lies with this part of code: "obj.put("Item", items);" as it's putting all the items in the same array, but how can I dynamically create different arrays? My list of items will keep expanding and will never be constant.
Code:
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();into the scope offorloop. In your case, you are using the sameitemsfor all different items.