2012-02-24 65 views
0

我想在這個URL解析JSON:解析JSON在Objective-C

http://maps.googleapis.com/maps/api/geocode/json?address=canada&sensor=false

在Objective-C

。我試圖讓在「邊界」東北緯度,這是我寫嘗試做到這一點(feedNSDictionary對象)的代碼:

NSArray *results = [feed objectForKey:@"results"]; 
NSDictionary *firstResult = [results objectAtIndex:0]; 
NSArray *geometry = [firstResult objectForKey:@"geometry"]; 
NSDictionary *firstGeo = [geometry objectAtIndex:0]; 
NSArray *bounds = [firstGeo objectForKey:@"bounds"]; 
NSDictionary *northeast = [bounds objectAtIndex:0]; 
NSString *neLat = [[NSString alloc] initWithString:[northeast objectForKey:@"lat"]]; 

即使它編譯罰款和JSON數據是有效的,當我運行它,我得到這個錯誤:

[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0xa672390 2012-02-24 01:32:06.321 Geo[570:11603] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0xa672390'

我不知道爲什麼會這樣,我順利拿到long_name前...任何幫助是極大的讚賞:)

謝謝提前!

回答

2

geometrybounds已經是詞典。

 "geometry" : { // <-- a dictionary! 
     "bounds" : { // <-- also a dictionary! 
      "northeast" : { 
       "lat" : 83.1150610, 
       "lng" : -52.62040200000001 
      }, 

所以,你應該寫

NSDictionary *geometry = [firstResult objectForKey:@"geometry"]; 
NSDictionary *bounds = [geometry objectForKey:@"bounds"]; 
NSDictionary *northeast = [bounds objectForKey:@"northeast"]; 
+1

請不要忘記'-valueForKeyPath:':'[firstResult valueForKeyPath:@「geometry.bounds.northeast」]' – nielsbot 2012-02-24 06:54:57

+0

@nielsbot:注意'-valueForKeyPath:'效率極低。 – kennytm 2012-02-24 11:23:11

+0

好吧,執行效率可能不高,但有效輸入! – nielsbot 2012-02-24 19:03:07

1

檢查下面的語句。

NSArray *geometry = [firstResult objectForKey:@"geometry"]; 

它似乎是geometry,它不返回NSArray。它返回NSDictionary