【发布时间】:2022-11-16 02:33:32
【问题描述】:
我正在尝试从 this JSON file from a URL 的 JSON 文件中返回 videoId
{
"kind": "youtube#searchListResponse",
"etag": "imd66saJvwX2R_yqJNpiIg-yJF8",
"regionCode": "US",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#searchResult",
"etag": "BeIXYopOmOl2niJ3NJzUbdlqSA4",
"id": {
"kind": "youtube#video",
"videoId": "1q7NUPF6j8c"
},
(示例中的正确返回是 1q7NUPF6j8c)。然后我想加载视频ID 一个
[self.playerView loadWithVideoId:@"the JSON video ID"];
到目前为止,我可以将整个 JSON 返回到日志:
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:@"https://i-doser.com/radio/livestream.json"]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
NSArray* json = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
NSLog(@"YouTube ID: %@", json);
//NSArray *videoid = [json valueForKeyPath:@"items.0.id.videoId"];
//NSLog(@"VideoID: %@", videoid);
}] resume];
这将返回到 NSLOG:
**App [6094:1793786] YouTube ID: {
etag = "imd66saJvwX2R_yqJNpiIg-yJF8";
items = (
{
etag = BeIXYopOmOl2niJ3NJzUbdlqSA4;
id = {
kind = "youtube#video";
videoId = 1q7NUPF6j8c;
};
kind = "youtube#searchResult";**
(以及其余的 json)。
我试过这是在黑暗中拍摄的。
//NSArray *videoid = [json valueForKeyPath:@"items.0.id.videoId"];
//NSLog(@"VideoID: %@", videoid);
但这返回空值。
我怎样才能只返回videoID并将其传递给self.playerView loadWithVideoId?
【问题讨论】:
-
使用
NSLog(@"YouTube ID: %@", json);的确切输出更新您的问题。顺便说一句——看起来json变量应该是NSDictionary,而不是NSArray。 -
正如它所说:到目前为止,我可以将整个 JSON 返回到日志中。所以, NSLog(@"YouTube ID: %@", json);当我试图仅返回 videoId 时返回整个 json。
-
至少显示从一开始到您想要的
videoID的 NSLog 语句的输出。关键是要确认您获得的实际结构是否符合您的预期。 -
它返回
nil,因为根对象是一个字典,注意开头的{。
标签: json objective-c