3

我有以下代码可以从我的服务器下载 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 文件中出现的顺序相同,但是当我用 枚举返回的 NSDictionary 时[dict allKeys],键会变得混乱,如下所示:

fourth key    
second key    
first key    
third key

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

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

4

1 回答 1

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]}
     ]
}

更新:

This thread could be useful for you Keeping the order of NSDictionary keys when converted to NSData with [NSJSONSerialization dataWithJSONObject:]

于 2014-03-18T14:23:30.153 回答