以正确的顺序获取JSONObject

时间:2015-06-11 16:00:08

标签: java json

我正在使用org.json库,我正在尝试以简单的形式创建JSON对象stops,如下所示,但我总是在同一个JSONArray timeEntries中获取所有timeArray并且名称始终在current output

中停止更改

当前输出:

{"arrival_time":
                {"mon-fri":[
                               ["04:48","05:18","05:46","06:16"],
                               ["04:52","05:22","05:50","06:20"],
                               ["04:57","05:27","05:56","06:26"]
                           ]
                },
"stops_name":"third name"}

代码:

    ArrayList<String> result = new ArrayList<String>();
    JSONObject stops = new JSONObject();
    JSONObject arrivals = new JSONObject();
    JSONArray arrivalMoFr  = new JSONArray();

    for (Entry<String, List<String>> entry : map.entrySet()) {
        String name = entry.getKey();
        List<String> timeEntries = entry.getValue();                        
        try {                       
        stops.put("stops_name", name);

        JSONArray timeArray = new JSONArray(timeEntries);
        arrivalMoFr.put( timeArray);

        arrivals.put("mon-fri", arrivalMoFr);

        stops.put("arrival_time", arrivals);

        System.out.println(stops.toString(3));
        } catch (JSONException e) {
            e.printStackTrace();
        }

简单的结果如何

{"arrival_time":
                {"mon-fri":["04:48","05:18","05:46","06:16"]

                }
"stops_name":"first name"},
{"arrival_time":
                {"mon-fri":["04:52","05:22","05:50","06:20"]

                }
"stops_name":"second name"},
{"arrival_time":
                {"mon-fri":["04:57","05:27", "05:56","06:26"]

                }
"stops_name":"third name"}

1 个答案:

答案 0 :(得分:3)

请记住,您希望数组作为根对象。您必须多次创建其他数组和对象,因此在for循环之外初始化它们是没有用的。

ArrayList<String> result = new ArrayList<String>();
JSONArray stops = new JSONArray();

for (Entry<String, List<String>> entry : map.entrySet()) {
    String name = entry.getKey();
    List<String> timeEntries = entry.getValue();                        
    try {
        JSONObject stop = new JSONObject();                     
        stop.put("stops_name", name);

        JSONArray timeArray = new JSONArray(timeEntries);
        //arrivalMoFr.put( timeArray);

        JSONObject arrivals = new JSONObject();
        arrivals.put("mon-fri", timeArray);

        stop.put("arrival_time", arrivals);
        stops.put(stop);

        //System.out.println(stops.toString(3));
    } catch (JSONException e) {
        e.printStackTrace();
    }
}