sarah
sarah

Reputation: 77

issue in looping

I am facing issue in looping in the following code,i am passing a list of forms to it,i am not sure what is going wrong,i need the output as but i am getting only the last form_id.I have this code to get this output as ,here i am passing a list of forms and getting the json as output. Please let me know where am i going wrong.

output :

{
    "forms": [
        { "form_id": "1", "form_name": "test1" },
        { "form_id": "2", "form_name": "test2" } 
    ]
}

code :

public class MyFormToJSONConverter {

   public JSONObject getJsonFromMyFormObject(List<Form> form) {

        JSONObject responseDetailsJson = new JSONObject();
        JSONArray jsonArray = null;
        List<JSONArray> list = new ArrayList<JSONArray>();
        System.out.println(form.size());
        for (int i = 0; i < form.size(); i++) {
               JSONObject formDetailsJson = new JSONObject();
               formDetailsJson.put("form_id", form.get(i).getId());
               formDetailsJson.put("form_name", form.get(i).getName());
               formDetailsJson.put("desc", 
                                    form.get(i).getFormDescription());
               jsonArray = new JSONArray();
               jsonArray.add(formDetailsJson);
               list.add(jsonArray);
        }

        for (JSONArray json : list) {
               responseDetailsJson.put("form", json);
        }

        return responseDetailsJson;
   }

Upvotes: 0

Views: 347

Answers (2)

cwallenpoole
cwallenpoole

Reputation: 82028

Your problem is here:

for (JSONArray json : list) {
     responseDetailsJson.put("form", json);
}

will overwrite all of the previous values with the next value (a single JSON object). You want

responseDetailsJson.put("form", list);

You probably should also get rid of this:

jsonArray = new JSONArray();
jsonArray.add(formDetailsJson);
list.add(jsonArray);

That will give you:

{
    "forms": [
        [{ "form_id": "1", "form_name": "test1" }],
        [{ "form_id": "2", "form_name": "test2" }] 
    ]
}

All told, I think you want:

JSONObject responseDetailsJson = new JSONObject();
List<JSONObject> list = new ArrayList<JSONObject>();
System.out.println(form.size());
// List.get will be very inefficient if passed a LinkedList 
// instead of an ArrayList.
for (Form formInstance:form) {
       JSONObject formDetailsJson = new JSONObject();
       formDetailsJson.put("form_id", formInstance.getId());
       formDetailsJson.put("form_name", formInstance.getName());
       formDetailsJson.put("desc", 
                            formInstance.getFormDescription());
       list.add(formDetailsJson);
}

responseDetailsJson.put("form", list);

Upvotes: 2

Brian Roach
Brian Roach

Reputation: 76898

JSON objects are essentially key/value pairs. In your code you are doing:

for (JSONArray json : list) 
{
    responseDetailsJson.put("form", json);
}

You're overwriting the same key each time.

Upvotes: 0

Related Questions