无法获取JSON字符串中的键,出现null

时间:2014-07-22 16:53:23

标签: objective-c json

当输出整个解析的JSON对象时,它工作正常,但是当尝试输出键的值时,它会出现(null)

解析代码:

-(NSString *)getNews{

__block NSString *strReturn;

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://URL/URL.json"]];

__block NSDictionary *json;
[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                           json = [NSJSONSerialization JSONObjectWithData:data
                                                                  options:0
                                                                    error:nil];

                               NSLog(@"Async JSON news: %@", json[@"ID"]);

                           //strReturn = json[@"ID"];
                       }];
return strReturn = @"Hello";

}

这是来自服务器上的JSON输出文件;

[{"ID":"1","Item Description":"Test News Item Active","News Text":"This is a test news story.\r\n\r\nit should have a few line breaks.\r\n\r\nbut that's about it.","Valid From":"2014-05-23 00:00:00","Valid To":"2014-09-30 23:59:59"}]

有人能告诉我为什么找不到密钥ID的价值吗?

1 个答案:

答案 0 :(得分:1)

JSON字典位于数组中。所以你必须正确引用它:

NSLog(@"Async JSON news: %@", [[json objectAtIndex:0] objectForKey:@"ID"]);