Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

com.google.gson.JsonPrimitive cannot be cast to com.google.gson.JsonObject ERROR

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..

like image 276
user3072054 Avatar asked Dec 26 '13 00:12

user3072054


1 Answers

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.

like image 123
Sotirios Delimanolis Avatar answered Oct 21 '22 11:10

Sotirios Delimanolis