我们如何通过JSON解析在iOS中检索数据?

时间:2014-04-23 05:37:23

标签: ios iphone json

我在我的应用程序中调用此方法。

[flickrRequest callAPIMethodWithPOST:@"flickr.photosets.create" arguments:[NSDictionary dictionaryWithObjectsAndKeys:FLICKR_AUTH_TOKEN,@"api_key",albumNAME,@"title",@"13978764555",@"primary_photo_id",@"Uploaded from my iPhone/iPod Touch", @"description", nil]];

JSON响应:

{ "photoset": { "id": "72157644227295321", "url": "https:\/\/www.flickr.com\/photos\/122586274@N04\/sets\/72157644227295321\/" }, "stat": "ok" }

我在我的日志猫上收到此回复,现在的问题是我想要检索这个" id"在我的申请中,但我无法做到这一点。请帮我解决这个问题?

2 个答案:

答案 0 :(得分:3)

从服务器返回数据后,您可以将其转换为NSDictionary

NSError *error;
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:dataFromServer options:NSJSONReadingMutableContainers error:&error];`

现在因为id在第二层,所以你可以做到

NSString *id = [[response objectForKey:@"photoset"] objectForKey:@"id"];

答案 1 :(得分:0)

确保在中执行nsjsonserialization - (void)connectionDidFinishLoading:(NSURLConnection *)connection 方法

您需要在@interface中创建一个实例变量,如下所示:

@interface TheClass: NSObject<NSURLConnectionDelegate>
{
    NSMutableData *_responseData;
}

然后以这种方式获取数据:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append the new data to the instance variable you declared
    [_responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
        NSError *error;
        NSDictionary *response = [NSJSONSerialization JSONObjectWithData:_responseData    options:NSJSONReadingMutableContainers error:&error];

}

在执行connectionDidfinishLoading方法之前,尚未收到所有数据。