循环中的问题

时间:2011-11-18 17:14:53

标签: java

我在循环中遇到以下代码问题,我正在传递一个表单列表,我不知道出了什么问题,我需要输出,但我只得到最后一个form_id.I有这个获取此输出的代码,这里我传递一个表单列表并将json作为输出。请告诉我哪里出错了。

输出:

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

代码:

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

2 个答案:

答案 0 :(得分:2)

你的问题在这里:

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

将使用下一个值(单个JSON对象)覆盖所有先前的值。你想要

responseDetailsJson.put("form", list);

你可能也应该摆脱这个:

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

那会给你:

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

总而言之,我想你想要:

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

答案 1 :(得分:0)

JSON对象本质上是键/值对。在您的代码中:

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

你每次都要覆盖相同的密钥。