com.google.gson.JsonPrimitive cannot be cast to com.google.gson.JsonObject ERROR
Asked Answered
S

1

9

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

Straightlaced answered 26/12, 2013 at 0:24 Comment(0)
D
11

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.

Diannadianne answered 26/12, 2013 at 16:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.