I have an NSString that is storing a JSON array in the form of a NSString. The NSString called colorArray has the value of:
[{ "color":"Red" },{ "color":"Blue" },{ "color":"Yellow"}];
I also have a tableview that I would like to import the array into in order to populate the table. The table works if I load the tableData into an array like below, but I can't figure out how to convert the NSString into an array that can be used to populate the tableData like shown below...
Anyone have ideas? Thanks much!
- (void)viewDidLoad
{
[super viewDidLoad];
// Initialize table data
tableData = [NSArray arrayWithObjects:@"Red", @"Blue", @"Yellow", nil];
}
// Your JSON data:
NSString *colorArray = @"[{ \"color\":\"Red\" },{ \"color\":\"Blue\" },{ \"color\":\"Yellow\"}]";
NSLog(@"colorArray=%@", colorArray);
// Convert to JSON object:
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:[colorArray dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:NULL];
NSLog(@"jsonObject=%@", jsonObject);
// Extract "color" values:
NSArray *tableData = [jsonObject valueForKey:@"color"];
NSLog(@"tableData=%@", tableData);
Output:
colorArray=[{ "color":"Red" },{ "color":"Blue" },{ "color":"Yellow"}]
jsonObject=(
{
color = Red;
},
{
color = Blue;
},
{
color = Yellow;
}
)
tableData=(
Red,
Blue,
Yellow
)
The last step uses the special feature of -[NSArray valueForKey:]
that returns an array containing the results of invoking valueForKey: using the key on each of the array's objects.
Try
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *jsonString = ...//String representation of json
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
//colors is a NSArray property used as dataSource of TableView
self.colors = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:nil];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.colors count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSDictionary *color = self.colors[indexPath.row];
cell.textLabel.text = color[@"color"];
return cell;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With