Reputation: 3
I'm trying to parse a JSON object in java :
{
"poster_path": "/e3QX3tY0fBR1GuxdP0mwpN16cqI.jpg",
"adult": false,
"overview": "In 1950s Pittsburgh, a frustrated African-American father struggles with the constraints of poverty, racism, and his own inner demons as he tries to raise a family.",
"release_date": "2016-12-16",
"genre_ids": [
18
],
"id": 393457,
"original_title": "Fences",
"original_language": "en",
"title": "Fences",
"backdrop_path": "/jNlCIAcheh0iOuL3kz9x1Wq9WLG.jpg",
"popularity": 10.976374,
"vote_count": 290,
"video": false,
"vote_average": 6.7
},
But I get a JSONException when I try to access the values for poster_path(org.json.JSONException: No value for poster_path) and release_date(org.json.JSONException: No value for release_date)
ArrayList<MovieModel> results = new ArrayList<MovieModel>();
String streamAsString = result;
try{
JSONObject jsonObject = new JSONObject(streamAsString);
JSONArray array = (JSONArray) jsonObject.get("results");
for (int i = 0; i < array.length(); i++) {
JSONObject c = array.getJSONObject(i);
JSONObject jsonMovie = array.getJSONObject(i);
MovieModel movieModel= new MovieModel();
movieModel.setMovieTitle(jsonMovie.getString("title"));
movieModel.setMovieGenre("na");;
String strImgURL=jsonObject.getString("poster_path").substring(2);
movieModel.setImgURL("");
movieModel.setMovieYear(jsonObject.getString("release_date"));
results.add((movieModel));
}
}
catch(JSONException j)
{
System.err.println(j);
Log.d(DEBUG_TAG, "Error parsing JSON. String was: " + j.toString());
}
Not sure what could be causing this error
Upvotes: 0
Views: 97
Reputation: 43322
You're trying to get the poster_path
and release_date
values from the outer JSONObject, the one that has everything (including the JSONArray that contains the individual movies).
In the loop, just use jsonMovie
instead of jsonObject
:
for (int i = 0; i < array.length(); i++) {
JSONObject jsonMovie = array.getJSONObject(i);
MovieModel movieModel= new MovieModel();
movieModel.setMovieTitle(jsonMovie.getString("title"));
movieModel.setMovieGenre("na");
String strImgURL=jsonMovie.getString("poster_path").substring(2);
movieModel.setImgURL("");
movieModel.setMovieYear(jsonMovie.getString("release_date"));
results.add((movieModel));
}
Upvotes: 3