我正在使用C#并使用YouTube V3 API。我试图在视频中插入注释但是每当我收到"{"Object reference not set to an instance of an object."}"
的异常时,只要我运行类似于上面代码的任何内容,就会发生这种情况:
public void AddComment()
{
CommentThread commentToAdd = new CommentThread();
commentToAdd.Snippet.IsPublic = true;
commentToAdd.Snippet.TopLevelComment.Snippet.TextOriginal = "Test";
commentToAdd.Snippet.VideoId = "kc-LBxBcyG8";
commentToAdd.Snippet.TopLevelComment.Snippet.VideoId = "kc-LBxBcyG8";
CommentThreadsResource.InsertRequest ins = JKYouTube.NewYouTubeService().CommentThreads.Insert(commentToAdd, "snippet");
var insertedComment = ins.Execute();
}
我将此与Google资源管理器进行比较并使用相同的属性,并且浏览器实际上会在我的程序失败时添加注释。 https://developers.google.com/youtube/v3/docs/commentThreads/insert
一旦到达第二行代码
commentToAdd.Snippet.IsPublic = true;
只会错误并继续上面的每一行。
非常感谢任何帮助。
答案 0 :(得分:2)
您的问题在于Snippet
是null
。
取自您提供的API link,您需要先创建一个CommentSnippet
。
在Google提供的示例中:
// Insert channel comment by omitting videoId.
// Create a comment snippet with text.
CommentSnippet commentSnippet = new CommentSnippet();
commentSnippet.setTextOriginal(text);
首先,使用一些文本创建CommentSnippet
,然后我们创建顶级评论:
// Create a top-level comment with snippet.
Comment topLevelComment = new Comment();
topLevelComment.setSnippet(commentSnippet);
然后,您将topLevelComment
添加到CommentThreadSnippet
:
// Create a comment thread snippet with channelId and top-level
// comment.
CommentThreadSnippet commentThreadSnippet = new CommentThreadSnippet();
commentThreadSnippet.setChannelId(channelId);
commentThreadSnippet.setTopLevelComment(topLevelComment);
当您最终拥有CommentThreadSnippet
时,可以将其添加到CommentThread
:
// Create a comment thread with snippet.
CommentThread commentThread = new CommentThread();
commentThread.setSnippet(commentThreadSnippet);
遵循这些步骤不应该给你一个NRE
答案 1 :(得分:0)
非常感谢你的帮助。管理完成它。
async Task AddVideoCommentAsync(string commentToAdd, string videoID)
{
CommentSnippet commentSnippet = new CommentSnippet();
commentSnippet.TextOriginal = commentToAdd;
Comment topLevelComment = new Comment();
topLevelComment.Snippet = commentSnippet;
CommentThreadSnippet commentThreadSnippet = new CommentThreadSnippet();
commentThreadSnippet.VideoId = videoID;
commentThreadSnippet.TopLevelComment = topLevelComment;
CommentThread commentThread = new CommentThread();
commentThread.Snippet = commentThreadSnippet;
var youtubeService = await NewYouTubeService();
CommentThreadsResource.InsertRequest insertComment = youtubeService.CommentThreads.Insert(commentThread, "snippet");
await insertComment.ExecuteAsync();
}