在AFJSONResponseSerializer之后,JSON NSDictionary无序

时间:2014-03-18 14:20:36

标签: ios objective-c json nsdictionary afhttprequestoperation

我有以下代码从我的服务器下载JSON文件:

- (void) queryAPI:(NSString*)query withCompletion:(void (^) (id json))block{
    NSURL *URL = [NSURL URLWithString:@"http://myAPI.example/myAPIJSONdata"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    op.responseSerializer = [AFJSONResponseSerializer serializer];
    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        block(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        block(nil);
    }];
    [[NSOperationQueue mainQueue] addOperation:op];
}

和JSON文件类似于以下示例:

{
    "dict":{
        "first key": [val1, val2, val3],
        "second key": [val1, val2, val3],
        "third key": [val1, val2, val3],
        "fourth key": [val1, val2, val3]
     }
}

我需要按照它们在JSON文件上的顺序保持密钥,但是当我使用[dict allKeys]枚举返回的NSDictionary时,我得到的密钥无序,如下所示:

fourth key    
second key    
first key    
third key

我也尝试使用[dict keyEnumerator],但结果完全一样。

有没有办法让密钥保持与JSON文件相同的顺序?

1 个答案:

答案 0 :(得分:2)

Cocoa中的NSDictionary不保持元素的顺序。因此,使用AFJSONResponseSerializer不可能将密钥保持在JSON文件中的相同顺序。您必须自己解析JSON或更改JSON结构以使用NSArray。

例如:

{
    [
        {"name" : "first key", "value" : [val1, val2, val3]},
        {"name" : "second key", "value" : [val1, val2, val3]},
        {"name" : "third key", "value" : [val1, val2, val3]},
        {"name" : "fourth key", "value" : [val1, val2, val3]}
     ]
}

更新:

这个帖子对你有用Keeping the order of NSDictionary keys when converted to NSData with [NSJSONSerialization dataWithJSONObject:]