【发布时间】:2014-04-20 20:56:43
【问题描述】:
我正在尝试读取我从 POST 请求中获得的 JSON。问题是,我无法获得嵌套字典。我试图保存 json,然后在我的 mac 上使用该文件,一切正常!我正在使用这种方法从服务器获取 JSON:
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!connectionError) {
if (![[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] isEqualToString:@"{\"response\":{\"status\":\"fail\",\"message\":\"Please use a POST request.\",\"code\":4012}}"]) {
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:@"/Users/David/Downloads/Test"] options:kNilOptions error:&error]; //This returns a other JSON than the JSON stored on my mac
NSArray *array = [dict objectForKey:@"list"];
NSMutableDictionary *mutableDict = [NSMutableDictionary new];
for (NSInteger i = 0; array.count>i; i++) {
NSDictionary *listDictionary = [array objectAtIndex:i];
NSDictionary *defenition = [listDictionary objectForKey:@"definition"];
[mutableDict setObject:[defenition objectForKey:@"form"] forKey:[listDictionary objectForKey:@"term"]];
}
NSLog(@"%@", mutableDict);
}
}
}];
现在的问题是,我必须使用其他方法从 NSURLConnection 获取正确的 JSON 吗?
谢谢
编辑
这是我下载的 json 和我的 mac 上的:
{
"response" : {
"status" : "success",
"code" : "200",
"message" : "OK"
},
"list" : [
{
"term" : "Black",
"context" : "",
"created" : "2014-04-17 20:34:33",
"updated" : "",
"definition" : {
"form" : "Schwarz",
"fuzzy" : 0,
"updated" : "2014-04-17 21:35:50"
},
"reference" : "",
"tags" : []
}
]
}
这是我从字典“dict”中得到的:
{
"response" : {
"status" : "success",
"code" : "200",
"message" : "OK"
},
"list" : [
{
"term" : "Black",
"context" : "",
"created" : "2014-04-17 20:34:33",
"updated" : "",
"reference" : "",
"tags" : []
}
]
}
注意,字典“定义”不见了!
【问题讨论】:
-
为什么要从文件中读取 JSON,而不是使用通过网络接收的数据(可能在 NSData 对象中)?
-
你为什么要使用那个时髦的字符串比较来检查失败?
-
你得到一个不同的值因为你正在从一个文件中读取。
-
(哪个版本存储在“/Users/David/Downloads/Test”中?)
标签: ios json nsurlconnection nsjsonserialization