2012-01-26 59 views
0

訪問JSON數據時,我有以下的JSON數據試圖目標C解析 - 我的代碼將返回空值,爲下級對象的值 - 用戶ID,名字和姓氏獲取空值從目標C

完整的JSON是:

{ 
    "members" : 
    [ 
     {"member" : {"userid":"1","FirstName":"ramesh","LastName":"babu"}}, 
     {"member" : {"userid":"2","FirstName":"ramesh2","LastName":"babu2"}}, 
     {"member" : {"userid":"3","FirstName":"ramesh3","LastName":"babu3"}} 
    ] 
} 

我的代碼是:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    dispatch_async(kBgQueue, ^{ 
     NSData* data = [NSData dataWithContentsOfURL: kLatestKivaLoansURL]; 
     [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES]; 
    }); 
} 

- (void)fetchedData:(NSData *)responseData { 
    //parse out the json data 
    NSError* error; 
    NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1 
                 options:kNilOptions 
                  error:&error]; 

    NSArray* members = [json objectForKey:@"members"]; //2 


    NSString *text1 = [json description]; 
    jsonSummary.text = text1; 

    NSEnumerator *e = [members objectEnumerator]; 
    NSArray *keys = [NSArray arrayWithObjects:@"userid", @"FirstName", @"LastName", nil]; 

    NSDictionary * member; 
    while (member = (NSDictionary *)[e nextObject]) { 
     // do something with object 
     // Iterate it 
     text1 = [member description]; 
     NSLog(@"MEMBER ROW DATA%@", text1); 
     for (id key in keys) { 

      text1 = [member description]; 
      NSLog(@"key: %@ value:%@ ", key, [member objectForKey:key]); 

     } 

    } 
} 

任何幫助,將不勝感激!

回答

1

根據示例JSON數據,「members」數組包含每個都有單個鍵「member」的字典。 「成員」鍵的值包含具有較低級別成員數據的字典。

您的代碼假定具有較低級別值的字典是數組元素,但它們不是。

您需要首先進入「成員」鍵值,然後獲取較低級別的值。

更改該行:

NSLog(@"key: %@ value:%@ ", key, [member objectForKey:key]); 

到:

NSLog(@"key: %@ value:%@ ", key, 
    [[member objectForKey:@"member"] objectForKey:key]); 

應該這樣做,雖然我會改變的變量名有點使它不那麼混亂。

+0

安娜,謝謝,我得到了關鍵值,發現成員dictionar y裏面有'member'對象。以下是有效的代碼。 –