我正在嘗試從 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?
uj5u.com熱心網友回復:
我認為你在正確的軌道上。我已將下面的示例 json 添加到您的示例 json 中,作為示例,其中"items"陣列中有多個專案用于說明目的:
{
"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"
},
},
{
"kind": "youtube#searchResult",
"etag": "secondETag",
"id": {
"kind": "youtube#video",
"videoId": "secondVideoId"
},
}
]
}
我首先注意到的一行代碼是您在決議 json 物件時期望使用 NSArray:
NSArray* json = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
根據您的示例輸入,您應該期望 NSDictionary 作為頂級物件:
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
現在進入valueForKeyPath
如果你要使用這樣的東西:
[jsonDict valueForKeyPath:@"items.id.videoId"]
您將獲得所有視頻 ID 的 NSArray:
(
1q7NUPF6j8c,
secondVideoId
)
然后你想要其中的第一個,這樣你就可以@firstObject用作“集合運算子”來獲取第一個物件。所以完整的關鍵路徑是:
NSString *videoId = [jsonDict valueForKeyPath:@"items.id.videoId.@firstObject"];
結果是:1q7NUPF6j8c
在此處使用集合運算子的鍵值編碼編程指南中有一些其他檔案:https ://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/KeyValueCoding/CollectionOperators.html#//apple_ref/doc/uid /20002176-BAJEAIEE
雖然在您可以使用的那個頁面上沒有明確說明(或記錄),但@firstObject這里有一些部分暗示了前幾段中的解決方案:
集合運算子是一小部分關鍵字中的一個,前面有一個 at 符號 (@),它指定 getter 應該執行的操作,以便在回傳資料之前以某種方式操作資料。
當鍵路徑包含集合運算子時,運算子之前的鍵路徑的任何部分(稱為左鍵路徑)指示相對于訊息接收者要對其進行操作的集合。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/533942.html
標籤:JSON目标-c
上一篇:排除引導程式容器的右邊距
