Jack Sparrow Jack Sparrow - 5 months ago 28
iOS Question

How to show nested JSON data in table view?

I have JSON like this

{ "StartElement": {
"Count": "14",
"Notification": [
{
"contact": null,
"Date": "20 June 2016",
"Message": null,
"Viewed": "1"
},
{
"contact": "99230332210",
"Date": "20 June 2016",
"Message": "I need help",
"Viewed": "1"
}
}


and my JSON parsing in
viewDidLoad
is this:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://www.someURL.com/JSONToFetch?"]];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"requestReply: %@", requestReply);
NSLog(@"code: %d",[(NSHTTPURLResponse*)response statusCode]);

}] resume];


Now, i want to show
"Message"
content into table view cells. How to store this data into array so i can load it into
cellForRowAtIndexPath
method. Thanx for help :)

Answer

If you want to get value for a particular key then you have to convert response in dictionary format and after conversion you can get value of particular key

Please convert your response like this

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"http://www.someURL.com/JSONToFetch?"]];
    [request setHTTPMethod:@"GET"];



   NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
            [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
   NSError *error;
   NSDictionary  *requestReply=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];//use Reading option NSJSONReadingAllowFragments because response contain array
                NSLog(@"requestReply: %@", requestReply);
                NSLog(@"code: %d",[(NSHTTPURLResponse*)response statusCode]);


NSArray *notification_list=[[requestReply valueForKey:@"StartElement"] valueForKey:@"Notification"];

            }] resume];