javaandroidarraysjson

I am getting a type error when looping JSONArray in Android / Java


I want to access posters and loop it in this JSON sting.

{"r":
    {"posters":
       [
        {"rev":10,"poster_id":4,"poster_filename":"545397373c2c7","poster_filepath":"\/poster_files\/545397373c2c7","poster_synopsis":"This is the new synopsis for this exquisite poster I have created. You will marvel at its greatness and ask many questions.","poster_title":"Poster A"},
        {"rev":6,"poster_id":7,"poster_filename":"5453b54b83b5f","poster_filepath":"\/poster_files\/5453b54b83b5f","poster_synopsis":"This is a synopsis that is not real. No one can say what this synopsis really means. It is total B.S..","poster_title":"Poster A"}
       ],
"msg":"72 & 2",
"status":"complete"}
}

I have this to convert the string to JSONObject:

JSONObject jsonObject = new JSONObject(result);         

JSONObject r = new JSONObject(jsonObject.getString("r"));

JSONArray posters = r.getJSONArray("posters");

Android Studio says "Array type expected, found org.json.JSONArray when I try to loop posters:

 int arraySize = posters.length();

 TextView myTextView = (TextView) findViewById(R.id.show_download_list);

 for(int i = 0; i < arraySize; i++) {
     myTextView.append(posters[i]);
     myTextView.append("\n");
 }

Am I not converting the object correctly??


Solution

  • JSONObject jsonObject = new JSONObject(result);         
    
    JSONObject r = jsonObject.getJSONObject("r");
    
    JSONArray posters = r.getJSONArray("posters");
    

    I changed the r JSONObject to get it from the JSONObject called r instead of calling string called r ,, because r in the json string is an object

    Update

    Change first line in the loop to be myTextView.append(posters.getJSONObject(i).getString("poster_title")); , this will print the poster title on each text view.