2012-03-01 51 views
0

我正在創建一個IPOD應用程序,並且我有一個從JSON提要創建的NSDictionary。我試圖將其轉換爲NSMutableArray。我知道我需要遍歷字典並將鍵和值寫入數組,但我遇到了代碼問題。這是完成這個的目的。iOS 5將NSDictionary轉換爲NSMutableArray的問題?

////從網站獲取JSON數據 NSError * error; NSDictionary * json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:& error];

////// convert the dictionary to an NSMutableArray 
// create an empty array of size equal to the number of json records 
NSMutableArray *users = [[NSMutableArray alloc] initWithCapacity:1];       
// Begin filling the array 
NSInteger dCount = [json count]; 

for(int i=0; i < dCount; i++) 
{ 
    User *user = [[User alloc] init]; 
    user.emailAddress = [json objectForKey: @"emailAddress"]; 
    user.password = [json objectForKey: @"password"]; 
    user.password = [json objectForKey: @"password"]; 
    [users addObject:user]; 
    NSLog(@"This is record: %@", i); 

}

在此先感謝。

回答

0

好可能不是最優雅的解決方案,但有很多的幫助,這是我想出了:

////////////////構建的陣列用戶在服務 dispatch_queue_t bgQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0); dispatch_async(bgQueue,^ {

////// Building users list 
//Get the data from the webserver 
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://msis-discussion-forum.appspot.com/users"]]; 

NSLog(@"Beginning to build array"); 
//// Get the JSON data from the website 
NSError* error; 
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 
NSLog(@"This is my JSON data %@", json); 
usersArray =[[NSMutableArray alloc]init]; 
NSArray *userJSONObjects = [json objectForKey:@"users"]; 
for (User *tempUser in userJSONObjects) 
{ 
    User *user = [[User alloc] init]; 
    user.displayName = [tempUser valueForKey:@"displayName"]; 
    NSLog(@"%@",user.displayName); 
    user.emailAddress = [tempUser valueForKey:@"emailAddress"]; 
    NSLog(@"%@",user.emailAddress); 
    user.password = [tempUser valueForKey: @"password"]; 
    NSLog(@"%@",user.password); 
    [usersArray addObject:user]; 
} 
}); 

希望它能幫助。