0

I have this json that i got using the YoutubeAPI :

{
 "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 "
   }
  }
]
}

i want to save the fiel "id" on an ArrayList but i have some problems this is the code im using:

JSONArray jsonArray = myResponse.getJSONArray("items");

In this line im creating an JSONarray with the JSONobject i created first

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();
    }
}

My question is how can i access to this field? and how can i save it

1
  • the videoId is a subProperty of an object called id Commented Oct 12, 2018 at 17:40

2 Answers 2

1

You've got two main issues. The first is that "videoID" and "videoId" are not the same string. So you're checking for a key that doesn't exist.

Your second problem is that the "videoId" key doesn't exist in the top level object, it's inside the "id" object, so you need to drill down an extra layer to get it:

    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]
Sign up to request clarification or add additional context in comments.

Comments

0

Try with correct case for videoId, like

list.add(json.getString("videoId"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.