gaer darrd
gaer darrd

Reputation: 35

new to json parsing - how to get an array within an array

from the following link , I need to get the value stored in "media".

Here is my code:

Content = Content.replace("jsonFlickrFeed(", "");
Content = Content.replace("})", "}");
jsonResponse = new JSONObject(Content);
JSONArray jsonMainNode = jsonResponse.optJSONArray("items"); // this works great!

But I can not access past "items"

Upvotes: 0

Views: 58

Answers (3)

ihsan
ihsan

Reputation: 586

You will have to loop through the JSON like this:

...
JSONArray jsonMainNode = jsonResponse.optJSONArray("items");

for (int i=0; i<jsonMainNode.length(); i++) {

    String media = jsonMainNode.getJSONObject(i).getString("media");
}

This will loop through the images and return the value(s) in media.

In your case it should be something like this:

..
JSONArray jsonMainNode = jsonResponse.optJSONArray("items");

for (int i=0; i<jsonMainNode.length(); i++) {

    JSONObject finalNode = jsonMainNode.getJSONObject(i);
    JSONArray finalArray = finalNode.optJSONArray("media");

    for (int j=0; j<finalArray.length(); j++) {
        String m = finalArray.getJSONObject(j).getString("m");
    }

}

...because there is another node inside the media node, called m.

Upvotes: 1

Mateusz Pryczkowski
Mateusz Pryczkowski

Reputation: 1894

JSONArray jsonMainNode = jsonResponse.optJSONArray("items"); // this works great!
            for (int i = 0; i < jsonMainNode.length(); i++) {
                JSONObject item = (JSONObject) jsonMainNode.get(i);
                JSONObject media = item.getJSONObject("media");
                String valueMedia = media.getString("m");
                Log.d("TAG", valueMedia);
            }

Upvotes: 0

RogueBaneling
RogueBaneling

Reputation: 4471

Here is an example getting the tags string for each item in the JSONArray that you have:

for (int i = 0; i < jsonMainNode.length(); i++){
    JSONObject jsonObject = jsonMainNode.getJSONObject(i);
    String tags = jsonObject.getString("tags");
}

This will iterate through all JSONObjects that are in the array, and extract the tags field from each object.

Upvotes: 1

Related Questions