2012-07-24 161 views
0

解析一些返回的JSON時遇到了一些麻煩。我對JSON的工作還很陌生。我試圖從第一個JSON數組元素中獲取公司名稱。我有一種感覺,我很困惑使用NSMutabeArray和NSMutableDictionary。我得到的是null。任何想法我做錯了什麼?返回null的JSON

NSString *url = @"http://www.google.com/finance/info?infotype=infoquoteall&q=C,JPM,AIG,AAPL"; 

NSData* data = [NSData dataWithContentsOfURL: 
       [NSURL URLWithString: url]]; 

//parse out the json data 
NSError* error; 
NSMutableArray* json = [NSJSONSerialization 
         JSONObjectWithData:data //1 

         options:kNilOptions 
         error:&error]; 

NSString* companyName = [[json objectAtIndex:0] objectForKey:@"name"] ; //Where I need some help 

NSLog(@"we got %@", companyName); 
+0

通過記錄下列值來幫助我們找出問題出現的地方:JSON字符串本身,'json','[json objectAtIndex:0]'。 – 2012-07-24 05:11:15

回答

3

在瀏覽器中加載該網址。看起來谷歌是用//加上JSON的前綴。我認爲NSJSONSerialization正在絆倒。試試這個

NSRange range = NSMakeRange(2, [data length] - 3); 
NSData *noPrefix = [data subdataWithRange:range]; 

然後發送到解析器。

2

你把一個錯誤對象,但你從來沒有看過它。如果你有,你會看到數據被破壞:

Error Domain = NSCocoaErrorDomain Code = 3840 "The data couldn’t be read because it has been corrupted." (Invalid value around character 1.) UserInfo = 0x10030a8f0 { NSDebugDescription = Invalid value around character 1. } 

我更改的選項參數的值,看看這個錯誤。我有

NSMutableArray* json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers |NSJSONReadingAllowFragments error:&error];