-3

我正在尝试在 iOS 中解析一些 JSON 以从 google 获取 URL。我已经走了很远(见下面的代码),问题是因为我以前从未使用过 JSON,我不太确定事情是如何定义的。如何查找位于另一个对象内的对象?

例如,如果我想在unescapedUrl 这里获得第一个,我该怎么做?我尝试简单地使用 objectForKey,但它没有用。我猜我将不得不指定确切的路径。我怎样才能做到这一点?

这是我正在使用的代码:

    #define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
    #define kLatestSearchURL [NSURL URLWithString: @"https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=monkey"] //2

    #import "ViewController.h"

    @interface NSDictionary(JSONCategories)
    +(NSDictionary*)dictionaryWithContentsOfJSONURLString:(NSString*)urlAddress;
    -(NSData*)toJSON;
    @end

    @implementation NSDictionary(JSONCategories)
    +(NSDictionary*)dictionaryWithContentsOfJSONURLString:(NSString*)urlAddress
    {
        NSData* data = [NSData dataWithContentsOfURL: [NSURL URLWithString: urlAddress] ];
        __autoreleasing NSError* error = nil;
        id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        if (error != nil) return nil;
        return result;
    }

    -(NSData*)toJSON
    {
        NSError* error = nil;
        id result = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:&error];
        if (error != nil) return nil;
        return result;
    }
    @end

    @implementation ViewController

    - (void)viewDidLoad
    {
        [super viewDidLoad];

        dispatch_async(kBgQueue, ^{
            NSData* data = [NSData dataWithContentsOfURL: kLatestSearchURL];
            [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
        });
    }

    - (void)fetchedData:(NSData *)responseData {
        NSError* error;
        NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
                                                             options:kNilOptions
                                                               error:&error];

// ---------------------------- Will Start Parsing Here ------------------------------
    }

    @end
4

2 回答 2

6

上帝保佑文字(Xcode 4.5 和 iOS 6.0 或更高版本的 SDK,需要 LLVM 编译器 4.0)。部署回 iOS 5。

NSString *url = resp[@"responseData"][@"results"][0][@"unescapedUrl"];
于 2013-02-10T12:19:57.237 回答
2

您可以objectForKey:用于字典和objectAtIndex:数组:

NSString *url = [[[[resp objectForKey:@"responseData"]
                        objectForKey:@"results"]
                        objectAtIndex:0]
                        objectForKey:@"unescapedUrl"];
于 2013-02-10T12:16:35.523 回答