gpt4 book ai didi

java - 以正确的顺序获取 JSONObject

转载 作者:行者123 更新时间:2023-11-29 05:04:41 26 4
gpt4 key购买 nike

我正在使用 org.json 库并尝试以如下所示的简单形式创建 JSON 对象 stops 但我总是得到所有 timeEntries 在同一个 JSONArray 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"}

最佳答案

请记住,您需要一个数组 作为您的根对象。您必须多次创建其他数组和对象,因此在 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();
}
}

关于java - 以正确的顺序获取 JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30785827/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com