如何在json中检索key的具体值?

时间:2017-03-26 04:12:48

标签: ios objective-c json

这是我的json内容。

 [  
  {  
    "sha":"30eae8a47d0203ac81699d8fc2ab2632de2d0bba",
     "commit":{  
     "author":{  
        "name":"Madhura Bhave",
        "email":"mbhave@pivotal.io",
        "date":"2017-03-23T23:14:32Z"
     },
     "committer":{  
        "name":"Madhura Bhave",
        "email":"mbhave@pivotal.io",
        "date":"2017-03-23T23:14:32Z"
     },
     "message":"Merge branch '1.5.x'",

   }
 }
 ]

这是我的main.i只想从消息和名称,电子邮件,日期从提交者字典中检索键值。我遇到了如何做到这一点。

    NSMutableArray *CommitArray = [[NSMutableArray alloc] init];


    for (NSDictionary *CommitDictionary in CommitJson) {
        CommitDict *commitDictObj = [[CommitDict alloc] init];
        commitDictObj.message = [CommitDictionary objectForKey:@"message"];

        for (NSDictionary *CommitterDictionary in [CommitDictionary objectForKey:@"committer"]) {
            Committer *author = [[Committer alloc] init];
            author.name = [CommitterDictionary objectForKey:@"name"];
            author.email = [CommitterDictionary objectForKey:@"email"];
            author.date = [CommitterDictionary objectForKey:@"date"];
        }

        [CommitArray addObject:commitDictObj];
    }




    for (int i =0 ; i < [CommitArray count] ; i++){
        CommitDict *commitDictObj = [CommitArray objectAtIndex:i];
        NSLog(@"Commit Message: %@", commitDictObj.message);



    }

     return 0;
}

}

我尝试获取json并显示消息,名称,电子邮件和日期的值。我可以记录消息,姓名,电子邮件和日期的值吗?

2 个答案:

答案 0 :(得分:0)

您的数组包含字典,该字典包含commit字典,而不是commit字典。替换你的代码部分:

for (NSDictionary *CommitDictionary in CommitJson) {
        CommitDict *commitDictObj = [[CommitDict alloc] init];

有了这个:

for (NSDictionary *shaCommitDictionary in CommitJson) {
        CommitDict *commitDictObj = [[CommitDict alloc] init];
        NSDictionary *CommitDictionary = [shaCommitDictionary objectForKey:@"commit"];

答案 1 :(得分:0)

(1)将JSON转换为NSDictionary

NSData *jsonData= ... // Assume you got the data already loaded
NSError *error = nil;    
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

(2)访问字典值(现在可用快速枚举!!

NSString *message = dictionary[@"message"];

NSDictionary *author = dictionary[@"author"];
NSString *name = author[@"author"];
NSString *email = author[@"author"];
NSString *date = author[@"author"];
// OR:
// NSString *name = dictionary[@"author"][@"author"];
// NSString *email = dictionary[@"author"][@"author"];
// NSString *date = dictionary[@"author"][@"author"];

就是这样。我认为棘手的事情是将JSON数据提供给NSDictionary? 见这里:https://stackoverflow.com/a/30561781/464016