2016-06-21 127 views
0

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

和我的JSON在viewDidLoad分析是這樣的:

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方法中。感謝名單爲幫助:)

+0

https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/你的反應首先閱讀。 – Joshua

回答

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

我試過,但'notification_list'仍然是空感謝,u能plz幫助我獲得所有'「消息」'到一個數組 –

+0

您的JSON是無效它不包含閉幕陣列 –

+0

是的,我糾正了 –

0

您可以保存您的回覆在字典

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 

從這個字典可以提取您的信息的NSArray,並用它到表

+0

是的,我用這個,您的幫助:) –

0

我想你的JSON解析是錯誤,你應該解析你的JSON到一個NSDictionary,並通知到一個NSArray.I建議你使用第三方JSON解析庫

相關問題