Reputation: 16841
I need to display the address
in a tableview
. How can i break the JSON
and save the addresses in an NSArray
.
The JSON is :
{
"Rank": 54,
"data": [
{
"number": 1,
"address": "x mandt "
},
{
"number": 2,
"address": "x mandt2 "
}
]
}
COde is:
NSDictionary *dic = (NSDictionary *) responseObject;
NSDictionary * dat = [dic objectForKey:@"data"];
NSArray *add =[dat objectForKey:@"address"];
The above code, doesn't retrieve and save all the address in the add
array. How can i solve this?
Upvotes: 0
Views: 226
Reputation: 4016
I think you better just use the literal syntax for retrieving this. The way you retrieve is just fine. You probably just add some introspection:
NSDictionary *responseDict = (NSDictionary *) responseObject;
if (responseDict.count) {
NSArray *dataArray = responseDict[@"data"];
if (dataArray.count) {
// do whatever you want
}
}
You made a mistake when you retrieve the key word data, you will get an array after that but not a NSDictionary.
Upvotes: 1
Reputation: 82759
assume that this is your serialization data
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
// here I start your work
NSArray *infoDict=[jsonArray objectForKey:@"data"];
for (NSDictionary *tmp in infoDict)
{
NSMutableDictionary *temparr=[[NSMutableDictionary alloc]init];
[temparr setValue:[tmp objectForKey:@"number"] forKey:@"number"];
[temparr setValue:[tmp objectForKey:@"address"] forKey:@"address"];
[_tdataSource addObject:temparr];
}
[yourtableviewNAme reloadData];
here I add the Tableview DataSource
and delegate
method
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section
{
return [self.tdataSource count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"resultCell";
yourtableviewCellName *cell = [self.yourtableName dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[yourtableviewCellName alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
}
cell.textLabel.text=[[self.tdataSource objectAtIndex:indexPath.row]objectForKey:@"address"];
return cell;
}
Upvotes: 1
Reputation: 11197
It should be:
NSArray *add =[dic objectForKey:@"data"];
Then if you want to have the address (I am considering address in 0'th index) then do this:
NSString *str = [[add objectAtIndex: 0] objectForKey:@"address"];
Edit:
Declare a class variable like:
@interface YourClassName (){
NSMutableArray *dataSource;
}
Populate the dataSource like:
dataSource =[dic objectForKey:@"data"];
Then In your cellForRowAtIndexPath
method do this:
cell.textLabel.text = [[dataSource objectAtIndex:indexPath.row] objectForKey:@"address"];
I am considering you have single section in your tableview. Hope this helps.. :)
Upvotes: 0