你们从来没有让我失望过,而且我在这个问题上处于紧张状态,我需要保持java地图的顺序,同时将其转换为JSON对象,我意识到这几乎是不可能的,并决定我会使用JSON数组。然而,这对我的特定数据有用的唯一方法是使用JSON对象的JSON数组。所以它看起来像这样:
[{"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}]
让我来到这里的代码:
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;
}
希望我的代码达到标准,尽量保持尽可能干净??? 但是回到了这个问题。这很好用,但是我遇到的问题是将这个对象数组转换为javascript中的关联数组,以便我可以将它用于我的D3js条形图这里是我愚蠢尝试但失败的代码
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;
};
任何想法?
答案 0 :(得分:0)
试试这个
var dateToArray = function(json_object) {
var dayArray = [],
key;
for (var i = 0; i < json_object.length; i++) {
key = Object.keys(json_object[i])[0];
dayArray.push({
"Date" : key,
"Count" : json_object[i][key]
});
}
return dayArray;
};
json_object 是Array not Object,您不应该使用 for (..in..) (for(.. in ..)语句迭代对象的可枚举属性)。在我的示例中,我使用 Object.keys 返回对象中的键数组,并且您可以通过Object中的键获取值,因为在JS中从对象获取属性有两种方式,如obj.key或者obj [key];