0

I would like to know how to loop through the JSON Array. Database looks like that:

{"Similar": {"Info": [{"Name": "Pulp Fiction", "Type": "movie"}], "Results": [{"Name": "Reservoir Dogs", "Type": "movie"}, {"Name": "Kill Bill", "Type": "movie"}, {"Name": "Jackie Brown", "Type": "movie"}

I am using an API call and I want to extract only the titles of the movies so I have e.g. "Reservoir Dogs", "Kill Bill" displayed in the log.

This code extracts "Reservoir Dogs" and shows it in the log:

@Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {

            try {

                JSONArray array = response.getJSONObject("Similar").getJSONArray("Results");

                String movie = String.valueOf(response.getJSONObject("Similar").getJSONArray("Results").getJSONObject(0).getString("Name"));

                Log.d("recommendMe", movie);

            } catch (JSONException e) {

                e.printStackTrace();

            }

        }

Unfortunately, to display all titles I would need to create at least several String variables, ten or twenty. So the question is, how to loop through this array to show all titles in one go?

Przemo
  • 111
  • 9

1 Answers1

0

You can use JSON.parse

Supose this is your json:

'{ "name":"John", "age":30, "city":"New York"}'

Send it to an obj:

var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');

Now you can use this way:

alert(obj.name);
alert(obj.age);
Marcelo Agimóvel
  • 1,668
  • 2
  • 20
  • 25