0

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 !!!

asked Apr 23, 2014 at 16:51

1 Answer 1

1

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);
answered Apr 23, 2014 at 17:07
Sign up to request clarification or add additional context in comments.

1 Comment

wow..thanks..never thought Map can be implemented this way...Thanks for the Heads Up dear...shall try to implement this code...Cheers!!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.