我在這裏經歷了類似的問題,但沒有找到我面臨的問題的答案。解析iOS中的JSON數據(Objective-c)並在TableView中顯示。獲取空值
我一直到現在都能夠解析JSON數據並存儲在字典中。這裏的JSON數據看起來像原始形式:
{"stores":[{"address":"7801 Citrus Park Town Center Mall","city":"Tampa","name":"Macy's","latitude":"28.068052","zipcode":"33625","storeLogoURL":"http://strong-earth-32.heroku.com/images/macys.jpeg","phone":"813-926-7300","longitude":"-82.573301","storeID":"1234","state":"FL"},
{"address":"27001 US Highway 19N","city":"Clearwater","name":"Dillards's","latitude":"27.9898988","zipcode":"33761","storeLogoURL":"http://strong-earth-32.heroku.com/images/Dillards.jpeg","phone":"727-296-2242","longitude":"-82.7294986","storeID":"1235","state":"FL"},
等..
正如你所看到的,它是字典的數組的字典。因此,我首先將原始數據存儲在字典中,將value
提取爲key = stores
並將其存儲在數組中。之後,我提取了每個字段並將其存儲在自定義對象tempStore中。這是失敗的時候。
- (void)viewDidLoad
{
[super viewDidLoad];
[populatedStoreArray addObject:@"blah"];
NSString *jsonRawData = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://strong-earth-32.heroku.com/stores.aspx"]];
if([jsonRawData length] == 0)
{
[jsonRawData release];
return;
}
SBJsonParser * parser = [[SBJsonParser alloc]init];
resultData = [[parser objectWithString:jsonRawData error:nil]copy];
NSArray *storeArray = [[NSArray alloc]init];
storeArray= [resultData objectForKey:@"stores"];
Store *tempStore = [[Store alloc]init];
/*NSLog(@"show me stores: %@", storeArray);*/
for(int i=1;i<[storeArray count];i++)
{
NSDictionary *tempDictionary = [storeArray objectAtIndex:i];
if([tempDictionary objectForKey:@"address"]!=nil)
{
tempStore.address= [tempDictionary objectForKey:@"address"];
//NSLog(@"Address: %@",tempStore.address);
}
//and so on for other keys
[populatedStoreArray addObject:tempStore];
NSLog(@"In array: %@",[populatedStoreArray objectAtIndex:i]);
}
這裏的tempStore對象:
- (id) init
{
if (self = [super init])
{
self.address = @"address";
self.city = @"city";
self.name = @"name";
self.latitude = @"latitude";
self.longitude = @"longitude";
self.state = @"state";
self.phone = @"phone";
self.storeid = @"storeID";
self.url = @"storeLogoURL";
self.zipcode = @"zipcode";
}
return self;
}
現在,我使用populatedStoreArray用於填充表格的單元格。我不確定要顯示的格式,但我主要關心的是當我嘗試打印populatedStoreArray時,即使tempStore已填充,其內容仍然爲空。 我在這裏錯過了什麼? 此外,populateStoreArray作爲屬性在.h文件中聲明。
@property (nonatomic, strong) NSMutableArray * populatedStoreArray;
在此先感謝。