我是iOS开发中的新手。我想从我的Web服务中解析JSON数据,因为我已经编写了以下代码
- (void)viewDidLoad
{
NSURL * url=[NSURL URLWithString:[NSString stringWithFormat:@"http://www.janvajevu.com/webservice/latest_post.php?page=%d",pageNum]];
dispatch_async(kBgQueue, ^{
data = [NSData dataWithContentsOfURL: url];
[self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
-(void)fetchedData:(NSData *)responsedata
{
if (responsedata.length > 0)
{
NSError* error;
self.json= [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
if ([[_json objectForKey:@"data"] isKindOfClass:[NSArray class]])
{
NSArray *arr = (NSArray *)[_json objectForKey:@"data"];
[self.navuArray addObjectsFromArray:arr];
[self.navuTable reloadData];
NSLog(@"JSON Data %@",self.navuArray);
}
self.navuTable.hidden=FALSE;
}
此处Self.json
是A JSON字典,self.navuArray
是我的NSMutableArray
,当我打印我的数组然后它返回Num。请给我解决方案。
答案 0 :(得分:2)
在从阵列向对象添加对象之前,未初始化的navuArray
。在调用数据之前对其进行初始化,然后向其中添加对象。
答案 1 :(得分:0)
试试此代码
id jsonObject = [NSJSONSerialization JSONObjectWithData:webData options:kNilOptions error:&error];
table = [[UITableView alloc]init];
[dict objectForKey:@"data"];
NSArray *array = (NSArray *)jsonObject;
if ([[dict objectForKey:@"data"] isKindOfClass:[NSArray class]])
{
for(int i=0;i<[array count];i++)
{
dict1 = [array objectAtIndex:i];
[postIdArr addObject:[dict objectForKey:@"post_id]];
[postTitleArr addObject:[dict objectForKey:@"post_title"]];
[postTitleSlungArr addObject:[dict objectForKey:@"post_title_slug"]];
NSString *dateId = [dict objectForKey:@"post_date"];
NSArray *dateArray = [dateId componentsSeparatedByString:@" "];
[dateArrs addObject:[dateArray objectAtIndex:0]];
[timeArrs addObject:[dateArray objectAtIndex:1]];
//[dateIdArr addObject:[dict objectForKey:@"date"]];
[postViewsArr addObject:[dict objectForKey:@"post_views"]];
[imageArr addObject:[dict objectForKey:@"feature_image"]];
[shortArr addObject:[dict objectForKey:@"short_description"]];
[nameArr addObject:[dict objectForKey:@"author_name"]];
}