将JSON响应提取到用于UITableview的属性列表中
我正在试图存储JSON响应像下面的财产权利表格图像的plist结构化。
我的回复:
{ "response": { "count": "1000", "girls": {}, "boys": { "0": { "name": "sam" }, "1": { "name": "jhon" }, "2": { "name": "keen" }, "3": { "name": "man" }, "4": { "name": "blue" } } } }
需要实现:
FYI:
存储所有的信息后,我需要得到Girls array
数据和基于segment
selectbutton的Boys array
数据它应该在桌面视图快速重新加载数据。
需要帮助:
如何获取像我发布的图像plist
结构的所有JSON
数据? 如何获取并加载到UItableview NSMutableArray
?
第一步:
将JSONstring转换为字典
NSError *jsonError; NSData *objectData = [strJSON dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&jsonError];
第二步:
为plist做一本字典
NSMutableDictionary * tempDict = [[NSMutableDictionary alloc] init]; [tempDict setObject:[[json objectForKey:@"response"] objectForKey:@"girls"] forKey:@"girls"]; [tempDict setObject:[[json objectForKey:@"response"] objectForKey:@"boys"] forKey:@"boys"];
最后一步:
将此字典写入pList文件
NSError *error; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"myPlistFile.plist"]; [tempDict writeToFile:plistPath atomically: YES];
编辑:如果你不想写这个词典plist文件,忽略最后一步。
只要使用你的tempDict作为tableView数据源。
段数: [[tempDict allKeys] count]
部分中的行数:
if (indexPath.section == 0) { return [[tempDict objectForKey:@"girls"] allKeys]; } else { return [[tempDict objectForKey:@"boys"] allKeys]; }
对于单元configuration,
if (indexPath.section == 0) { lblTitle.text = [[[tempDict objectForKey:@"girls"] objectForKey:[NSString stringWithFormat:@"%d",indexPath.row] objectForKey:@"name"]; } else { lblTitle.text = [[[tempDict objectForKey:@"boys"] objectForKey:[NSString stringWithFormat:@"%d",indexPath.row] objectForKey:@"name"]; }
希望对你有帮助….
请参阅下面的解决scheme示例
NSDictionary *dictionary = @{@"response": @{ @"count": @"1000", @"girls": @{}, @"boys": @{ @"0": @{@"name": @"sam"}, @"1": @{@"name": @"jhon"}, @"2": @{@"name": @"keen"}, @"3": @{@"name": @"man"} } } }; //return boys count while loading boys. return [[[dictionary valueForKey:@"response"] valueForKey:@"boys"] allKeys].count; //return girls count while loading boys. return [[[dictionary valueForKey:@"response"] valueForKey:@"girls"] allKeys].count; //Use this in cell for indexpath for row. NSDictionary *boys = [[dictionary valueForKey:@"response"] valueForKey:@"boys"]; NSString *nameString = [[boys valueForKey:[NSString stringWithFormat:@"%ld",(long)indexPath.row]] valueForKey:@"name"]; //To get all name of boys at once NSArray *boysName = [boys valueForKeyPath:@"name"];