从JSON端点检索数据

时间:2016-01-09 06:17:28

标签: ios objective-c json

我使用Drupal iOS SDK在我的ViewController中使用以下代码从实体(评论)中检索数据:

ViewController.h

@property (nonatomic, strong) NSMutableArray *comments;
@property (weak, nonatomic) IBOutlet UILabel *userReviews;

ViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];

    NSDictionary *entityData = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"1"] forKey:@"uid"];

    [DIOSEntity
     entityGet:entityData
     name:@"entity_comment"
     eid:@"uid"
     success:^(AFHTTPRequestOperation *op, id response) {
         self.comments = [NSMutableArray arrayWithObject:(NSDictionary*)response];


         NSLog(@"This is all of the data from response %@", response);
         dispatch_async(dispatch_get_main_queue(), ^(void){
           //  [self.tableView reloadData];
         });
     }
     failure:^(AFHTTPRequestOperation *op, NSError *err) { NSLog(@"failed to get data"); }
     ];

返回JSON数据并在我的控制台中显示如下:

2016-01-08 21:53:13.213 app[2382:935044] Comments are as follows (
    {
        changed = 1450564731;
        cid = 1;
        "comment_body" =         {
            und =             (
                                {
                    format = "filtered_html";
                    "safe_value" = "<p>Christina is amazing with pets; I would recommend her to all users.</p>\n";
                    value = "Christina is amazing with pets; I would recommend her to all users.";
                }
            );
        };
) 

我试图显示从&#34; comment_body&#34;中返回的内容。在UILabel中(端点的XML看起来像这样):

<comment_body>
<und is_array="true">
<item>
<value>
Christina is amazing with pets; I would recommend her to all users.
</value>
<format>filtered_html</format>
<safe_value>
<p>Christina is amazing with pets; I would recommend her to all users.</p>
</safe_value>
</item>
</und>
</comment_body>

我的问题:为了检索该行,代码应该是什么样的?我认为它应该看起来像......

self.userReviews.text = [self.comments objectForKey:@"comment_body"];

但是注释是一个NSMutableArray(因此,该行无法工作)。任何帮助表示赞赏;谢谢!

2 个答案:

答案 0 :(得分:1)

试试这个

 self.userReviews.text = [[[[[self.comments objectAtIndex:0] objectForKey:@"comment_body"] objectForKey:@"und"] objectAtIndex:0] objectForKey:@"value"];

答案 1 :(得分:0)

使用NSDictionary,如下所示:

 { 
        NSDictionary *jsonDictionary= [NSDictionary alloc]init]
             jsonDictionary= response;

            self.userReviews.text=[[[[jsonDictionary valueForKey:@"comment_body"]valueForKey:@"und"]objectAtIndex:0]objectForKey:@"value"]; 
}