0

I am currently developing an app and need to parse JSON objects from inside an unnamed array.
I can only manage to parse JSON arrays with a name such as this one: http://jsonparsing.parseapp.com/jsonData/moviesDemoItem.txt.

The code that I used for the one above is

protected String doInBackground(String... params) {

        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer buffer = new StringBuffer();

            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }


            String asd = buffer.toString();

           JSONObject parentObject = new JSONObject(asd);
           JSONArray parentArray = parentObject.getJSONArray("movies");
           JSONObject fObject = parentArray.getJSONObject(0);

            String movie = fObject.getString("movie");
            int year = fObject.getInt("year");

            return movie + year;

The code includes "movies" which is the array name .
What should I change to parse only the objects from within a JSON array such as https://restcountries.eu/rest/v1/all?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • 1
    You should ideally either return `buffer.toString()` or `parentObject` from `doInBackground`. Do the remaining JSON parsing in `onPostExecute`. – OneCricketeer Oct 28 '16 at 16:53
  • Possible duplicate of [How to parse JSON in Android](http://stackoverflow.com/questions/9605913/how-to-parse-json-in-android) – OneCricketeer Oct 28 '16 at 16:54

1 Answers1

3

Your countries list is simply an array. Doesn't need a name.

Simply replace

JSONObject parentObject = new JSONObject(asd);

with

JSONArray parentObject = new JSONArray(asd);

See this post for how to iterate over that array to parse the remainder of the objects.

How to parse JSON in Android

Starting something like

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

Alternatively, Volley's JsonArrayRequest would be useful, or learning about Retrofit+Gson would be even better if you don't feel like manually parsing the JSON data yourself.

Community
  • 1
  • 1
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245