Reputation: 1
I am trying to fetch the data from the database and then trying to set the values in the JSON document using ArrayList but i am not able to do that. Lets say this is hard code JSON which i want to convert it into dynamic JSON view plainprint? Note: Text content in the code blocks is automatically word-wrapped
String json = "{ \"demo\":[[ \"Sam\",\"Sola\",\"Accun\"],[\"Raj\",\"Sanjosh\",\"CA\"],[\"Karan\",\"Toshi\",\"Java\"]]}";
Now, to embed the JSON rows dynamically , i have used ArrayList as follows : view plainprint? Note: Text content in the code blocks is automatically word-wrapped
ArrayList<Object> al = new ArrayList<Object>();
.............some database code..........
while (result.next()) {
al.add("[ \"" + result.getString(1) + "\",
\""+ result.getString(3) + "\",
\"" + result.getString(4)+ "\",
\"" + result.getString(5) + "\",
\""+ result.getString(6) + "\",
\"" + result.getString(7)+ "\",
\"" + result.getString(8) + "\"]");
}
Now i want to embed this collection into the JSON document. but not sure how to do this. view plainprint? Note: Text content in the code blocks is automatically word-wrapped
String h = "{ \"demo\":[ "+
for(Object o : al){
}
+"]}";
Please Guide me to get through this....Thanks !!!
Upvotes: 0
Views: 134
Reputation: 10955
Instead of manually trying to construct the json, you would be better off using one of the existing libraries. It looks like the json you are trying to generate is a simple mapping, so you could do something like this:
List<String> list = new ArrayList<String>();
list.add(result.getString(1));
list.add(result.getString(3));
//etc
Map<String, List<String>> map = new HashMap<String, List<String>>();
map.put("demo", list);
String json = new Gson().toJson(map);
Upvotes: 1