2012-03-01 55 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]; 
} 
}); 

希望它能帮助。

相关问题