2013-10-14 75 views
4

我可以檢索JSON對象並顯示它,但是如何從「lat」和「lng」中獲取用於Xcode的值?如何使用NSJSONSerialization從JSON對象獲取值

我的代碼:

NSString *str=[NSString stringWithFormat:@"https://www.<WEBSITE>]; 
NSURL *url=[NSURL URLWithString:str]; 
NSData *data=[NSData dataWithContentsOfURL:url]; 
NSError *error=nil; 

NSDictionary* dictionary = [NSJSONSerialization JSONObjectWithData:data 
                  options:kNilOptions 
                  error:&error]; 
NSLog(@"Your JSON Object: %@ Or Error is: %@", dictionary, error); 

JSON對象:

(
    { 
    response =   { 

     lat = "52.517681"; 
     lng = "-115.113995"; 

    }; 
} 

我似乎無法訪問任何數據。我已經試過:

NSLog(@"Value : %@",[dictionary objectForKey:@"response"]); 

我也嘗試了一堆變化的像

NSLog(@"Value : %@",[[dictionary objectForKey:@"response"] objectForKey:@"lat"]); 

但它總是以大跌結束了:

-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x15dd8b80 

我注意到,當我正在通過調試'字典'只包含1個對象。如何將我的JSON對象轉換爲帶密鑰對的NSDictionary?這個JSON對象是錯誤的格式還是什麼?

+0

是否有上述反應的關鍵?如果你斷行並將鼠標懸停在NSDictionary對象上,你應該能夠看到內容。 –

+1

你看到了什麼?它是一個包含一個名爲「response」的條目的元素的數組。該條目又是一個包含「lat」和「lng」兩個元素的字典。 –

+1

你的問題顯然是你不能剝離陣列。 (上面稱爲「字典」的是一個數組。) –

回答

5

該特定的JSON對象是一個NSArray,而不是一個NSDictionary,這就是爲什麼它不能識別選擇器,並且您沒有收到警告,因爲NSJSONSerialization JSONObjectWithData返回一個id。

嘗試

NSArray *array = [NSJSONSerialization JSONObjectWithData:data 
               options:kNilOptions 
                error:&error]; 
NSDictionary *dictionary = array[0]; 
+0

@Hbombre還指出,在這些現代時代,我們一般喜歡用括號表示法來訪問字典對象,例如'dictionary [@「response」]'。閱讀通常比較容易,但顯然是一種風格選擇,所以你不必遵守。 – JuJoDi

-3

下面是一個應用程序,我寫了喀嚓...基本上得到NSData的對象,通常是從響應,並使用NSJSONSerialization JSONObjectWithData:選項:錯誤,這將產生一個的NSDictionary

NSError *error = nil; 
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error]; 

//Make sure response came in 
if(response != nil){ 
    NSError *error = nil; 
    id data = [NSJSONSerialization JSONObjectWithData:response options:0 error:&error]; 

    if([data isKindOfClass:[NSDictionary class]]){ 
     //Create dictionary from all the wonderful things google provides 
     NSDictionary *results = data; 

     //Search JSON here 
     NSArray *cityAndState = [[[[results objectForKey:@"results"] objectAtIndex:0] objectForKey:@"address_components"] valueForKey:@"short_name"]; 
+0

如果您覺得這篇文章可以改進,請考慮留言。 –

+0

@HotLicks現在是不是難以理解? –

+2

對,現在幾乎看不見。 –

0

看來,JSON返回的不是一個NSDictionnary對象,但一個NSArray。改變你的代碼是這樣的:

NSarray *responseArray = [NSJSONSerialization JSONObjectWithData:data 
                  options:kNilOptions 
                  error:&error]; 

的responseArray包含dictionnary對象(或多少?),那麼你ACN ACCES主題是這樣的:

For (NSDictionary *dic in responseArray){ 
    NSDictionnary *response = [dic [email protected]"response"]; 
.... 
}