我正在尝试从提供JSON的Web服务获取一些数据。但我不知道我的代码出了什么问题。它看起来很简单但我无法获得任何数据。
这段代码:
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
AFJSONRequestOperation *operation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
DumpDic = (NSDictionary*)[JSON valueForKeyPath:@"description"] ;
}
failure:nil
];
[operation start];
AboutTXT = [DumpDic objectForKey:@"description"];
这是JSON URL。
修改
来自网址的JSON:
{
"clazz":"AboutList",
"description":{
"clazz":"DescriptionContent",
"description":"ASTRO Holdings Sdn. Bhd. (AHSB) Group operates through two holding companies – ASTRO Overseas Limited (AOL) which owns the portfolio of regional investments and ASTRO Malaysia Holdings Sdn Bhd (AMH / ASTRO) for the Malaysian business, which was privatized in 2010 and is currently owned by Usaha Tegas Sdn Bhd/its affiliates, and Khazanah Nasional Berhad."
},
"id":{
"inc":-1096690569,
"machine":1178249826,
"new":false,
"time":1339660115000,
"timeSecond":1339660115
},
"refKey":"AboutList"
}
答案 0 :(得分:13)
是否成功连接到服务器,是否正在调用成功块?
填写故障块和NSLog失败块返回的NSError:
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"%@", [error userInfo]);
}
我还有一个提示,我建议使用AFNetwork的AFHTTPClient构建NSURLRequest,它可以帮助处理各种事情,并且通常可以使事情更简单。您设置基本URL,然后为其添加一个附加到该基础的路径。像这样:
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:address];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
NSMutableURLRequest *jsonRequest = [httpClient requestWithMethod:@"POST"
path:@"events"
parameters:dict];
我也建议您只使用objectForKey:
而不是使用valueForKeyPath[JSON objectForKey:@"description"];
此外,你不应该在那里访问DumpDic:
[operation start];
AboutTXT = [DumpDic objectForKey:@"description"];
这是一个异步调用,所以一旦操作开始,DumpDic很可能在从服务器分配数据之前被访问。所以你正在访问一个可能还不存在的密钥。
这应该在成功或失败块中完成。一旦连接完成并且数据准备好被使用,就会调用这些块。
所以看起来应该更像这样:
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
DumpDic = [JSON objectFor:@"description"];
AboutTXT = [DumpDic objectForKey:@"description"];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"%@", [error userInfo]);
}];
[operation start];