将返回的json数据保存到NSDictionary或NSArray以在TableView中显示?

时间:2014-01-12 15:41:05

标签: ios iphone objective-c json uitableview

我正在提取JSON数据,并试图弄清楚如何将循环的每个密钥保存到字典中以显示在我的TableView中。

我的代码:

-(void)fetchedDetailData:(NSData *)responseData {

    NSError* error;
    NSDictionary* json = [NSJSONSerialization
                          JSONObjectWithData:responseData

                          options:kNilOptions
                          error:&error];

    NSDictionary* placeDetails = [json objectForKey:@"result"];
    NSString *taxiName = [placeDetails objectForKey:@"name"];
    NSString *taxiPhoneNumber = [placeDetails objectForKey:@"international_phone_number"];

    parsedDict = [[NSMutableDictionary alloc] init];
    [parsedDict setValue:taxiName forKey:@"name"];
    [parsedDict setValue:taxiPhoneNumber forKey:@"international_phone_number"];
    NSLog(@"%@", parsedDict);

}

似乎日志输出:

2014-01-12 10:38:59.864 B[720:70b] {
    "international_phone_number" = "+1 508-760-0000";
    name = "All Points Taxi";
}
2014-01-12 10:38:59.928 B[720:70b] {
    "international_phone_number" = "+1 508-564-7500";
    name = "Bourne Bridge 24HR Taxi";
}
2014-01-12 10:38:59.936 B[720:70b] {
    "international_phone_number" = "+1 508-524-8818";
    name = "Barnstable Taxi and Limo";
}
2014-01-12 10:38:59.950 B[720:70b] {
    "international_phone_number" = "+1 508-221-1804";
    name = "Cape & Islands Air Taxi";
}
2014-01-12 10:39:00.114 B[720:70b] {
    "international_phone_number" = "+1 508-775-5555";
    name = "Town Taxi of Cape Cod Inc";
}

看起来它覆盖了每一个,而不是添加每一个。对于从Google商家信息获取的每个引用,都会在for循环中调用此方法。不确定我到底出错的地方,只是试图将每个出租车的每个电话号码和名称保存到一个NSDictionary中,以便在Tableview中显示。

1 个答案:

答案 0 :(得分:0)

NSDictionary会覆盖您nameparsedDict相同密钥的值。所以你需要一个数组来保存你的解析数据。

@property(nonatomic, strong) NSMutableArray *parsedList; 

if(!parsedList){
    parsedList = [[NSMutableArray alloc] init];
}
NSMutableDictionary *parsedDict = [[NSMutableDictionary alloc] init];
[parsedDict setValue:taxiName forKey:@"name"];
[parsedDict setValue:taxiPhoneNumber forKey:@"international_phone_number"];
[self.parsedList addObject:parsedDict];
NSLog(@"%@", self.parsedList);