如何在表视图中显示嵌套的JSON数据?

时间:2016-06-21 08:59:04

标签: ios objective-c json

我有像这样的JSON

    {   "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"
          }
     }

我在viewDidLoad中的JSON解析是这样的:

 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];

现在,我想在表格视图单元格中显示"Message"内容。如何将这些数据存储到数组中,以便我可以将其加载到cellForRowAtIndexPath方法中。 Thanx寻求帮助:)

3 个答案:

答案 0 :(得分:0)

您可以将回复保存在词典中

Google App Engine

通过这本词典,您可以将消息提取到NSarray并将其用于表格

答案 1 :(得分:0)

我认为您的JSON解析是错误的,您应该将您的JSON解析为NSDictionary,并将通知解析为NSArray。我建议您使用第三方JSON解析库

答案 2 :(得分:0)

如果您想获得特定键的值,那么您必须以字典格式转换响应,转换后您可以获得特定键的值

请转换您的回复

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];