2014-11-16 54 views
-3

當我搜索This Link to JSON file時,它不返回任何內容(resultCount = 0)。這是我正在嘗試做的一些代碼。我如何從iOS中的Json獲得一定的價值?

NSData *data = [[NSData alloc] initWithContentsOfURL:@"https://itunes.apple.com/search?term=EMINEMLFLOCKAFLOCKA&entity=song&limit=3" options:NSDataReadingUncached error:&error]; 
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; 
NSString *resultCount = [JSON valueForKey:@"resultCount"]; 

// Does not return anything 
NSLog(@"%@", resultCount); 

我不明白爲什麼resultCount不會返回任何東西。這段代碼不存儲它的值(0)嗎?如何從resultCount中檢索數據?我試圖從中獲得像0,1,2或3這樣的值。

+0

你是什麼意思 「RESULTCOUNT個不返回任何東西」 是什麼意思? 'resultCount'是一個'NSNumber'(但你錯誤地將它用作'NSString')。這不是一個功能。你期望它能「返回」什麼?如何? **你看過這個URL提供的JSON並意識到'resultCount'確實是0嗎?** –

+0

A)你是否證實'data'是非空的? B)你是否證實'JSON'是非空的? C)爲什麼你不使用'error'參數? D)你爲什麼不在'JSON'中向我們展示價值? –

+0

@TheParamagneticCroissant它顯示數據中沒有任何內容(如果!數據的語句運行)。這是否意味着我無法獲得resultCount值? – abc123abc

回答

1

我很驚訝你沒有得到編譯器警告(和崩潰)解決這個問題,但你有兩個問題:

  1. 不能initWithContentsOfUrlNSString,你必須通過它的NSURL
  2. 您應該將resultCount解析爲NSInteger而不是NSString

修正:

NSError* error = [NSError new]; 
NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"https://itunes.apple.com/search?term=EMINEMLFLOCKAFLOCKA&entity=song&limit=3"] options:NSDataReadingUncached error:&error]; 
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; 
NSInteger resultCount = [[JSON valueForKey:@"resultCount"] intValue]; 

// Logs 0 
NSLog(@"%ld", resultCount);