4

我正在尝试从提供 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

编辑

来自 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"
}
4

1 回答 1

13

是否成功连接到服务器,是否调用了成功块?

填写失败块并 NSLog 失败块返回的 NSError:

failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
                                                        NSLog(@"%@", [error userInfo]);
                                                    }

我还有一个提示,我建议使用 AFNetwork 的 AFHTTPClient 构建 NSURLRequest,它有助于处理各种事情,并且通常会使事情变得更简单。您设置基本 URL,然后为其提供附加到该基本 URL 的路径。像这样的东西:

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:address];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
NSMutableURLRequest *jsonRequest = [httpClient requestWithMethod:@"POST"
                                                            path:@"events"
                                                      parameters:dict];

另外,我建议您不要使用 valueForKeyPath,而是只做一个 objectForKey:

[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];
于 2012-06-14T15:07:40.767 回答