我正在使用 Youtube Api 获取 channel ID,但我遇到了错误。
我读了这个答案 JSONException: No value for photo 但它无法解决我的问题。
这是一些 JSON 代码。
{
"kind":"youtube#activityListResponse",
"etag":"\"8jEFfXBrqiSrcF6Ee7MQuz8XuAM/OMMhc8F-t0SORJfXv_Owv4A3N_g\"",
"nextPageToken":"CAUQAA",
"pageInfo":{
"totalResults":20,
"resultsPerPage":5
},
"items":[
{
"kind":"youtube#activity",
"etag":"\"8jEFfXBrqiSrcF6Ee7MQuz8XuAM/WUtPyfC60sUnCViYyIHtr7rKu5E\"",
"id":"VTE1NjcxMTI0MzYxNDAyNDEzMTcwNzczOTI=",
"snippet":{
"publishedAt":"2019-08-29T21:00:36.000Z",
"channelId":"UC_x5XG1OV2P6uZZ5FSM9Ttw",
"title":"Android Studio 3.5, Cloud Run Button, BigQuery Terraform module",
这是java代码
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
Log.i("jsonObject ", jsonObject.toString());
String items= jsonObject.getString("items");
JSONArray arr = new JSONArray(items);
for (int i=0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
Log.i("ID",jsonPart.getString("channelId"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
我希望它会在 logcat 中显示此结果
"channelId":"UC_x5XG1OV2P6uZZ5FSM9Ttw"
但它显示此错误“JSONException:channelId 没有值”
最佳答案
您想要的 JSONArray
的名称为 items
,而不是 snippets
。
你必须做这样的事情:
String items = jsonObject.getString("items");
JSONArray arr = new JSONArray(items);
for (int i=0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
JSONObject snippet = new JSONObject(jsonPart.getString("snippet"))
Log.i("ID",snippet.getString("channelId"));
}
关于java - 如何从 Youtube Api 获取 channel ID?它显示此错误 "JSONException: No value for channelId",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57728675/