Mukie
Mukie

Reputation: 129

How to fetch a specific key from a dictionary having multiple arrays and store into string placed in table view cell

Here are the labels placed in the tableView Cells with name a, b, c, d

//Want to store passenger_no here
    cell.a.text; 
//Want to store depart_city here
    cell.b.text; 
//Want to store name here
cell.d.text; 

Here am fetch the JSON data and storing into array of name array and storing that array into dictionary named as dict

NSArray *array = [_json valueForKey:@"result"];
NSDictionary *dict = array[indexPath.row];

The JSON looks like this :

{ "result": [
        { "passenger_no": 4,
          "destination_detail": [
                { "depart_city": "Indira Gandhi International"}],
          "aircraft_info": [{ "name": "CEAT 450"}]
}]}

Upvotes: 1

Views: 38

Answers (2)

Kazunori Takaishi
Kazunori Takaishi

Reputation: 2398

In cellForRowAtIndexPath: method, you can assign fetched value to text label in your cell like this:

NSArray *array = [_json valueForKey:@"result"];
NSDictionary *dict = array[indexPath.row];

//Want to store passenger_no here
cell.a.text = [dict valueForKey:@"passenger_no"];

//Want to store depart_city here
NSArray *destinationDetails = [dict valueForKey:@"destination_detail"];
NSDictionary *departcityInfo = destinationDetails.firstObject;
cell.b.text = [departcityInfo valueForKey:@"depart_city]"

//Want to store name here
NSArray *aircraftInfoList = [dict valueForKey:@"aircraft_info"];
NSDictionary *aircraftInfo = aircraftInfoList.firstObject;
cell.d.text = [aircraftInfo valueForKey:@"name"];

PS. In Modern Objective-C Syntax, you can access value of NSDictionary by dict[@""passenger_no"] instead of [dict valueForKey:@"passenger_no"].

Hope this helps!

Upvotes: 1

Vinodh
Vinodh

Reputation: 5268

So in cellforrowatindexpath your code will be like below

NSDictionary *dict = array[indexPath.row];
    NSArray *destinationdetailarray = [dict valueForKey:@"destination_detail"];
    NSString *departcity = [[destinationdetailarray firstObject]valueForKey:@"depart_city"];
    NSString *passengerno = [NSString stringWithFormat:@"%@",[dict valueForKey:@"passenger_no"]];
    NSArray *aircraftinfo = [dict valueForKey:@"aircraft_info"];
    NSString *name = [[aircraftinfo firstObject]valueForKey:@"name"];

Upvotes: 0

Related Questions