我正在使用Youtube Api来获取频道ID,但我遇到了错误。
我读了这个答案JSONException: No value for photo 但这无法解决我的问题。
这是一些JSON代码。
<div class="container">
<span class="text" contenteditable="true">Lorem ipsum dolor </span>
<span before-content="Tag" contenteditable="true"> sed dignissim maximus mattis </span>
<span before-content="Tag" contenteditable="true"> vel ex ut nisi elementum tincidunt libero</span>
</div>
这是Java代码
{
"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",
我希望它将在logcat中显示此结果
@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();
}
}
但显示此错误“ JSONException:channelId没有值”
答案 0 :(得分:1)
您想要的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"));
}