我相信你要找的是NSJSONSerialization。
這個答案假定使用NSURLConnection的基於塊的API來執行你的GET。
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (data) {
NSError *jsonError = nil;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
if (dict) {
// You got a valid NSDictionary out of your JSON response.
NSLog(@"my returned dictionary: %@", dict);
} else if (jsonError) {
// JSON data could not be parsed into NSDictionary. Handle as appropriate for your application.
return;
}
} else if (connectionError) {
// Handle connection error
}
}];
但即使您使用的是dataWithContentsOfURL :,點也是一樣的。將您的數據輸入到NSJSONSerialization的+ jsonObjectWithData:options:error:方法中,檢查是否從中得到了字典,然後繼續。
編輯:如果您正在爲NSDictionary的HTTP請求創建JSON發佈主體,那麼NSJSONSerialization也包含在其中。
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:someDictionary options:NSJSONWritingPrettyPrinted error:&error];
if (data) {
// You got your data.
NSLog(@"my data: %@", data);
[someURLRequest setHTTPBody:data];
} else if (error) {
NSLog(@"error: %@", [error localizedDescription]);
}
JSON或賈森? – Dev 2014-12-04 12:13:59
誰是_JASON?_ – holex 2014-12-04 12:36:29