You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从YouTube API的JSON响应中提取snippet下的title和description字段

问题根因

你的代码没有匹配API返回的JSON嵌套结构:items数组的每个子元素下,title和description并非直接挂载在item对象下,而是包裹在snippet对象中,你直接从data[i]层级读取这两个字段就会返回空值。

修改后的实现代码

public void SetVideoInfo(string videoID)
{
    var url = new RestClient("https://www.googleapis.com/youtube/v3/videos?part=snippet&fields=items(snippet(title,description))&id=" + videoID + "&key=somekey");
    url.Timeout = -1;

    var urlRequest = new RestRequest(Method.GET);
    var urlResponse = url.Execute(urlRequest);
    var response = JObject.Parse(urlResponse.Content);
    var data = (JArray)response["items"];

    for (int i = 0; i < data.Count; i++)
    {
        // 先取snippet对象,再读取其下的title和description
        var snippet = data[i]["snippet"];
        var videoTitle = snippet["title"];
        var videoDescription = snippet["description"];

        this.VideoTitle = videoTitle.ToString().Trim();
        this.VideoDescription = videoDescription.ToString().Trim();
    }
}

核心修改点

  • 新增snippet对象读取逻辑,先从data[i]中获取snippet属性,再从snippet中读取title和description即可正确拿到对应值。

内容的提问来源于stack exchange,提问作者seacode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 05:57:02