Reputation: 1708
I am using org.json
library and am trying to create JSON Object stops
in the simple form as below but I am always getting all timeEntries
in the same JSONArray timeArray
and the name is always changes in the stops as in the current output
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"}
Code:
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();
}
Simple how should the result like
{"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"}
Upvotes: 1
Views: 132
Reputation: 22651
Keep in mind that you want an array as your root object. You'll have to create the other array and objects multiple times, so initializing them outside the for
loop isn't useful.
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();
}
}
Upvotes: 3