Converting an NSString of JSON Data to NSArray
32,087
Solution 1
// 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.
Solution 2
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;
}
Solution 3
NSData * data = [colorArray dataUsingEncoding:NSUTF8StringEncoding]
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData: data
options: NSJSONReadingMutableContainers
error: &e];
NSArray *tableData = [JSON valueForKey:@"color"];
Hope this helps..
Author by
Brandon
Updated on May 06, 2020Comments
-
Brandon about 4 years
I have an
NSString
that is storing aJSON
array in the form of aNSString
. TheNSString
calledcolorArray
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 theNSString
into an array that can be used to populate thetableData
like shown below...Anyone have ideas? Thanks much!
- (void)viewDidLoad { [super viewDidLoad]; // Initialize table data tableData = [NSArray arrayWithObjects:@"Red", @"Blue", @"Yellow", nil]; }