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

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);
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

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.