以有序的方式从NSDictionary获取密钥

时间:2018-04-27 05:55:39

标签: ios objective-c json sorting nsdictionary

我有这样的JSON响应:

 {
    "graphdata": {
        "2018-02-27 to 2018-03-05": {
            "historical": 2.93,
            "datewise": 2.82,
            "ordno": 3595,
            "revno": 89
        },
        "2018-03-06 to 2018-03-12": {
            "historical": 2.92,
            "datewise": 2.62,
            "ordno": 3780,
            "revno": 87
        },
        "2018-03-13 to 2018-03-19": {
            "historical": 2.92,
            "datewise": 3.16,
            "ordno": 3742,
            "revno": 86
        },
        "2018-03-20 to 2018-03-26": {
            "historical": 2.93,
            "datewise": 3.17,
            "ordno": 3745,
            "revno": 70
        },
        "2018-03-27 to 2018-04-02": {
            "historical": 2.93,
            "datewise": 3.08,
            "ordno": 4242,
            "revno": 84
        },
        "2018-04-03 to 2018-04-09": {
            "historical": 2.93,
            "datewise": 3.29,
            "ordno": 3575,
            "revno": 79
        },
        "2018-04-10 to 2018-04-16": {
            "historical": 2.94,
            "datewise": 3.19,
            "ordno": 3629,
            "revno": 69
        },
        "2018-04-17 to 2018-04-23": {
            "historical": 2.94,
            "datewise": 3.33,
            "ordno": 4211,
            "revno": 42
        },
        "2018-04-24 to 2018-04-30": {
            "historical": 2.94,
            "datewise": 0,
            "ordno": 1638,
            "revno": 0
        }
    }
}

现在,当我使用allKeys方法时,我会以无序方式获取Keys:

(
    "2018-03-13 to 2018-03-19",
    "2018-04-03 to 2018-04-09",
    "2018-03-20 to 2018-03-26",
    "2018-04-10 to 2018-04-16",
    "2018-04-17 to 2018-04-23",
    "2018-04-24 to 2018-04-30",
    "2018-03-27 to 2018-04-02",
    "2018-02-27 to 2018-03-05",
    "2018-03-06 to 2018-03-12"
)

如何以有序的方式获取这些内容,例如:#34; 2018-02-27至2018-03-05",

4 个答案:

答案 0 :(得分:0)

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd"];
NSArray *sortedArray = [yourArray sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
    NSDate *d1 = [df dateFromString: obj1];
    NSDate *d2 = [df dateFromString: obj2];
    return [d1 compare: d2];
}];

注意:根据您的日期设置日期格式

答案 1 :(得分:0)

(((jsonDict.object(forKey: "graphdata") as! NSDictionary).allKeys) as! [String]).sorted(by: <) as NSArray

这里jsonDict是你的父NSDictionary

答案 2 :(得分:0)

每个字典都是一组无序的键值对。

  

需要订购时使用DictionaryLiteral实例   键值对的集合,不需要快速键查找   字典类型提供。

答案 3 :(得分:0)

我使用sortedArrayUsingComparator:

解决了这个问题
   NSArray *sortedKeys = [[myDictionary allKeys] sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
        return [a compare:b];
    }];