我有使用 YoutubeAPI 获得的 json :
{
"items": [
{
"id": {
"videoId": "ob1ogBV9_iE"
},
"snippet": {
"title": "13 estrellas ",
"description": "Pueden encontrar estas "
}
},
{
"id": {
"videoId": "o9vsXyrola4"
},
"snippet": {
"title": "Rayos Cósmicos ",
"description": "Este es un programa piloto "
}
}
]
}
我想将字段“id”保存在 ArrayList 上,但我遇到了一些问题,这是我使用的代码:
JSONArray jsonArray = myResponse.getJSONArray("items");
在这一行中,我使用首先创建的 JSONobject 创建一个 JSONarray
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject json = jsonArray.getJSONObject(i);
list.add(json.getString("videoID"));
} catch (JSONException e) {
e.printStackTrace();
}
}
我的问题是如何访问此字段?以及如何保存它
最佳答案
您有两个主要问题。首先是 "videoID"
和 "videoId"
不是同一个字符串。因此您正在检查不存在的 key 。
您的第二个问题是 "videoId"
键不存在于顶级对象中,它位于 "id"
对象内部,因此您需要钻取再往下一层即可得到它:
JSONArray jsonArray = myResponse.getJSONArray("items");
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject json = jsonArray.getJSONObject(i);
JSONObject id = json.getJSONObject("id");
list.add(id.getString("videoId"));
} catch (JSONException e) {
e.printStackTrace();
}
}
System.out.println(list); // [ob1ogBV9_iE, o9vsXyrola4]
关于java - 将 JsonArray 转换为 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52784415/