2012-10-21 65 views
0

我從URL中檢索json數據。 json「string」有一個包含多個對象的對象,每個對象都包含它們自己的鍵值屬性......實際上,json對象是一個NSArray,它包含的對象或多或少是字典對象。我試圖用NSJSONSerialization但沒有大量的文檔資料就可以了,我似乎無法弄清楚如何在這裏的JSON可能看起來像一個例子:解析包含多個對象的JSON字符串

{"allObjects":[{"firstName":"homer","middleName":"j","lastName":"simpson" 
,"address": "123 evergreen terrace","countryCode":"US","zip":12345}, 
{"firstName": "marge","middleName":"b","lastName":"simpson","address": 
"123 evergreen terrace","countryCode":"US","zip":12345}]} 

(如果很重要,JSON對象包含許多條目)

是否需要使用NSJSONSerialization來獲取字典數組(數組爲「allObjects」)的特定「選項」?

任何幫助將不勝感激!

在此先感謝。

UPDATE

一個錯誤這段代碼的結果:

@vishy我認爲這太,但是當我運行此代碼,

NSArray *json = [NSJSONSerialization JSONObjectWithData:geoNamesJSON options: kNilOptions error:&error]; 
NSDictionary *dict = [json objectAtIndex:0]; 
NSArray *allKeys = [dict allKeys]; 
NSString *key = [[NSString alloc] init]; 
NSEnumerator *keyEnum = [allKeys objectEnumerator]; 
NSLog(@"All keys in the first dictionary object:"); 
while(key = [keyEnum nextObject]){ 
    NSLog(@"%@", key);} 

我得到這個錯誤:

-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x1fd7cd10 * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x1fd7cd10' * First throw call stack: (0x3796c2a3 0x35c7c97f 0x3796fe07 0x3796e531 0x378c5f68 0xf310b 0xf219d 0x38ca4321 0x38cdecfd 0x38d53cc1 0x38cd86a7 0x38cd8481 0x38c52abb 0x38cc78d7 0x355b9bd9 0x3665c4b7 0x366611bd 0x3793ff3b 0x378b2ebd 0x378b2d49 0x37def2eb 0x38c91301 0xd3551 0x3c39db20) libc++abi.dylib: terminate called throwing an exception (lldb)

+0

的JSON字典之後。 。 解析任何JSON你應該知道你的JSON格式,然後只有你可以寫你的解析代碼.. – vishy

+0

@vishy我更新了我的問題(無法弄清迷你Markdown)與使用此方法的問題。 – jpcguy89

回答

1

你是否在數組後獲得任何值做這一步

NSArray *json = [NSJSONSerialization JSONObjectWithData:geoNamesJSON options:kNilOptions error:&error]; 

我不這麼認爲,因爲你的json是一本字典。它應該是

NSDictionary* json = [NSJSONSerialization JSONObjectWithData:geoNamesJSON options:kNilOptions error:&error]; 

有關處理json的信息,你可以關注這個tutorial

編輯:解析所述數據以這種方式得到使用上述線

NSArray* geoList = [geoDict objectForKey:@"geonames"]; 
NSLog(@"first object in geolist--%@",[geoList objectAtIndex:0]); 
//each object in the array is a dictionary 
在給定json-它與在其內一個對象的字典其是2個字典陣列
+0

作爲你在序列化後得到字典你可以打印並檢查它是哪種格式..你可以顯示數據日誌..? – vishy

+0

GEONAMES =( { adminCode1 = *省略* adminName1 = *省略* COUNTRYCODE = *省略* 國家名稱= *省略* 距離= 「*省略*」; FCL = *省略*; fclName =「 *省略* 「; FCODE = *省略*; fcodeName = *省略*; geonameId = *省略*; LAT = 」*省略*「; LNG = 」*省略*「; 名稱=」 *省略*「; population = 0; toponymName = * OMITTED *; }); – jpcguy89

+0

這裏'='是什麼&wat是'geonames'根據這個json只有一個字典,它作爲字符串(對象)和鍵。 – vishy

相關問題