I'm trying to parse the JSON data from the Rotten Tomatoes API using GSON in Android. I can get some of it parsed, but I seem to be having trouble with the arrays inside of my base result object.
Here is my "MovieObject" class:
package ---;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class MovieObject {
public List<Rating> ratings; //You are a problem
@SerializedName("id")
public String id;
@SerializedName("title")
public String title;
@SerializedName("year")
public int year;
@SerializedName("mpaa_rating")
public String mpaaRating;
@SerializedName("runtime")
public int runtime;
@SerializedName("critics_consensus")
public String criticsConsensu;
@SerializedName("synopsis")
public String synopsis;
@SerializedName("studio")
public String studio;
}
I can successfully pull fields such as title
, id
and year
but can not access fields in my Rating class (public List<Rating> ratings
)
Here is the Rating class:
package ---
import com.google.gson.annotations.SerializedName;
public class Rating {
@SerializedName("critics_rating")
public String criticsRating;
@SerializedName("critics_score")
public int criticsScore;
@SerializedName("audience_rating")
public String audienceRating;
@SerializedName("audience_score")
public int audienceScore;
}
Here is some excerpts from my activity related to how I'm trying to get the data. Which works, for the most part.
InputStream source = retrieveStream(url);
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
MovieObject mObject = gson.fromJson(reader, MovieObject.class); //Expected BEGIN_ARRAY but was BEGIN_OBJECT instead. Something to do with the Rating object I believe.
Toast.makeText(this, mObject.title, Toast.LENGTH_SHORT).show();
Toast.makeText(this, mObject.synopsis,Toast.LENGTH_SHORT).show();
The problem arises when I try to do something like this:
List<Rating> ratings = mObject.ratings;
for (Rating rating : ratings) {
Toast.makeText(this, rating.criticsScore,Toast.LENGTH_SHORT).show();
}
The error shown is:
Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 28 column 362
If I comment out the part in MovieObject
where I declare the Ratings variable... things work. So that seems to be the issue. BUT I'm not sure how to get around that. Would it be easier to just do native Android JSON parsing instead of trying to use GSON? Or mess with Jackson?
For reference, here is the api viewer for the Rotten Tomatoes response: http://jsonviewer.stack.hu/#http://api.rottentomatoes.com/api/public/v1.0/movies/770672122.json?apikey=vg2cj5tgqmbkkxz2vgyxqyh9
Well, that's because the ratings field is NOT an array:
"ratings": {
"critics_rating": "Certified Fresh",
"critics_score": 99,
"audience_rating": "Upright",
"audience_score": 91
},
It's an object. So, just declare it as public Ratings ratings;
abridged_directors
, for example, IS a list:
"abridged_directors": [
{
"name": "Lee Unkrich"
}
],