gpt4 book ai didi

ios - AFJSONResponseSerializer 后 JSON NSDictionary 困惑

转载 作者:搜寻专家 更新时间:2023-10-30 20:17:57 25 4
gpt4 key购买 nike

我有以下代码可以从我的服务器下载一个 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]}
]
}

更新:

此线程可能对您有用 Keeping the order of NSDictionary keys when converted to NSData with [NSJSONSerialization dataWithJSONObject:]

关于ios - AFJSONResponseSerializer 后 JSON NSDictionary 困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22482163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com