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

如何通过YouTube API获取Channel Id?遇JSONException无channelId值报错

解决JSONException: No value for channelId问题

嘿,我一眼就发现问题出在哪啦!你看返回的JSON结构,channelId并不是直接在items数组的每个元素对象里,而是嵌套在**snippet子对象**里面的。你的代码直接从jsonPart里取channelId,自然会找不到这个字段啦。

咱们先确认下JSON的层级结构:

"items":[ 
  { 
    "kind":"youtube#activity",
    "etag":"\"8jEFfXBrqiSrcF6Ee7MQuz8XuAM/WUtPyfC60sUnCViYyIHtr7rKu5E\"",
    "id":"VTE1NjcxMTI0MzYxNDAyNDEzMTcwNzczOTI=",
    "snippet":{ 
      "publishedAt":"2019-08-29T21:00:36.000Z",
      "channelId":"UC_x5XG1OV2P6uZZ5FSM9Ttw", // channelId实际在这里
      "title":"Android Studio 3.5, Cloud Run Button, BigQuery Terraform module"
    } 
  } 
]

你原来的代码里,这一步是错误的:

// 错误:直接从activity对象中取channelId
Log.i("ID",jsonPart.getString("channelId"));

修正后的代码

你需要先从jsonPart里拿到snippet子对象,再从snippet中提取channelId:

@Override 
protected void onPostExecute(String s) { 
    super.onPostExecute(s); 
    try { 
        JSONObject jsonObject = new JSONObject(s); 
        Log.i("jsonObject ", jsonObject.toString()); 
        // 直接获取items数组,无需先转成String
        JSONArray arr = jsonObject.getJSONArray("items"); 
        for (int i=0; i < arr.length(); i++) { 
            JSONObject jsonPart = arr.getJSONObject(i); 
            // 先获取snippet对象
            JSONObject snippet = jsonPart.getJSONObject("snippet");
            // 再从snippet中取出channelId
            String channelId = snippet.getString("channelId");
            Log.i("ID", channelId);
        } 
    } catch (Exception e) { 
        e.printStackTrace(); 
    } 
}

另外小提醒:原来的代码里把items先转成String再转JSONArray是多余的,直接用jsonObject.getJSONArray("items")更简洁也能避免潜在的格式问题~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:07:37