- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我有以下代码可以从我的服务器下载一个 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 文件中的顺序相同?
最佳答案
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]}
]
}
更新:
关于ios - AFJSONResponseSerializer 后 JSON NSDictionary 困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22482163/
我有以下代码可以从我的服务器下载一个 JSON 文件: - (void) queryAPI:(NSString*)query withCompletion:(void (^) (id json))bl
我有 AFNetworking 2.0 的问题。 我在我的应用中将其用作单例。 一些请求有类似 JSON 格式的类型响应,其他请求有一个简单的 HTTP 状态。 因此,在某些请求中我必须使用 AFJS
在安装 GM Xcode 6.1 之前,以下代码运行良好。但是在安装 Xcode 6.1 之后,出现错误: 我试过了,错误非常好。 有什么想法吗?我还没有阅读发行说明。 最佳答案 只是一个猜测,但请尝
我是一名优秀的程序员,十分优秀!