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