我有以下代码从我的服务器下载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文件?
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]}
]
}
更新:在使用[NSJSONSerialization dataWithJSONObject:]转换为NSData时,保持NSDictionary键的顺序