You guys never let me down and I am kind of in a tight spot on this one, I needed to maintain the order of a java map while converting it into a JSON object, I realized that this was nearly impossible and decided that I would use a JSON array. The only way that this would work for my particular data however was to use a JSON array of JSON objects. so it looks like this:
[{"2014-11-18":0},{"2014-11-19":0},{"2014-11-20":0},{"2014-11-21":0},{"2014-11-22":0},{"2014-11-23":0},{"2014-11-24":0}]
the code that got me here:
public static JSONArray dataGenerationDay(ArrayList<String> comp, int days) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("MM-dd-yyyy");
Map<LocalDate, Integer> compMap = new TreeMap<LocalDate, Integer>();
JSONArray orderedJSON = new JSONArray();
//create map of data with date and count
for (String date : comp) {
DateTime dt = formatter.parseDateTime(date);
LocalDate dateTime = new LocalDate(dt);
if (!compMap.containsKey(dateTime)) {
compMap.put(dateTime, 1);
} else {
int count = compMap.get(dateTime) + 1;
compMap.put(dateTime, count);
}
}
//if there were days missing in the DB create those days and put them in the map
//with a zero count
if (compMap.size() < days){
LocalDate today = LocalDate.now();
for (int i = 0; i < days; i++){
LocalDate dayCount = today.minusDays(days- i);
if (!compMap.containsKey(dayCount)) {
compMap.put(dayCount, 0);
}
}
}
//json object does not hold order of tree map, create json array
//of ?json objects? to maintain order for the graph
for (Map.Entry<LocalDate,Integer> entry : compMap.entrySet()){
JSONObject object = new JSONObject();
object.put("" + entry.getKey(), entry.getValue());
orderedJSON.put(object);
//test the order of the map for validity
System.out.println("Key Value Pair Is: " + entry.getKey() + " : " + entry.getValue());
}
//test the order of the array for validity
System.out.println("Ordered JSON List: " + orderedJSON.toString());
return orderedJSON;
}
Hope my code is up to par, trying to keep it as clean as possible??? However back to the issue. This works great, the problem I am having however is converting this array of objects into an associative array in javascript so that I can use it for my D3js bar graph here is the code that I foolishly tried but failed with
var dateToArray = function(json_object) {
var dayArray = [];
for (key in json_object){
dayArray.push({
"Date" : key[0],
"Count" : json_object[key[1]]
});
}
console.log("Here is su array" + dayArray);
return dayArray;
};
Any Ideas?