When i try to parjse the json object from thelist i get an error com.google.gson.JsonPrimitive cannot be cast to com.google.gson.JsonObject
Input:
{
"r$contentRatings": [
{
"r$scheme": "urn:rt",
"r$rating": "criticSummaryScore=-1,criticSummaryCount=0,criticSummaryCertified=false,criticSummaryRotten=false,fanSummaryScore=75,fanSummaryCount=4"
}
]
}
Code:
JsonElement elem = null;
elem = jsonObject.get("r$contentRatings");
if(elem != null) {
JsonArray contentRatingsList = elem.getAsJsonArray();
if(contentRatingsList != null) {
for(int i=0; i< contentRatingsList.size(); i++) {
JsonObject scheme =contentRatingsList.get(i).getAsJsonObject().getAsJsonObject("r$scheme");
JsonObject rating =contentRatingsList.get(i).getAsJsonObject().getAsJsonObject("r$rating");
JsonArray subRatings = contentRatingsList.get(i).getAsJsonObject().getAsJsonObject("r$subRatings").getAsJsonArray();
Error:
Inside the for loop, when i try to access the jsonobject
from the list r$scheme
I get an error
com.google.gson.JsonPrimitive cannot be cast to com.google.gson.JsonObject
Can you please let me know how to get rid of this error..
Simply, in your json
{
"r$contentRatings": [
{
"r$scheme": "urn:rt",
"r$rating": "criticSummaryScore=-1,criticSummaryCount=0,criticSummaryCertified=false,criticSummaryRotten=false,fanSummaryScore=75,fanSummaryCount=4"
}
]
}
The elements r$scheme
and r$rating
are not json objects, but json primitives.
Use
JsonPrimitive scheme = contentRatingsList.get(i).getAsJsonObject().getAsJsonPrimitive("r$scheme");
JsonPrimitive rating = contentRatingsList.get(i).getAsJsonObject().getAsJsonPrimitive("r$rating");
Also, note that you have no element named r$subRatings
in your json so you are setting yourself up for a NullPointerException
in the next line.