Error on JsonElement cannot be convert to JsonObject

1.1k views Asked by At

so there is a jsonReqObj,

jsonReqObj = {
 "postData" : {
     "name":"abc",
     "age": 3,
     "details": {
        "eyeColor":"green",
        "height": "172cm",
        "weight": "124lb",
   }
 }
}

And there is a save function that will return a string. I want to use that save function, but the input parameter for the save json should be the json inside postData.

public String save(JsonObject jsonReqObj) throw IOException {
...
 return message
}

below are my code

JsonObject jsonReqPostData = jsonReqObj.get("postData")

String finalMes = save(jsonReqPostData);

But I am getting the error that

com.google.gson.JsonElement cannot be convert to com.google.gson.JsonObject. 
2

There are 2 answers

0
new_programmer On

I have validated your JSON file with https://jsonlint.com/ and it looks like the format is incorrect, instead of be:

jsonReqObj = {
    "postData": {
        "name": "abc",
        "age": 3,
        "details": {
            "eyeColor": "green",
            "height": "172cm",
            "weight": "124lb",
        }
    }
}

Should be:

{
    "postData": {
        "name": "abc",
        "age": 3,
        "details": {
            "eyeColor": "green",
            "height": "172cm",
            "weight": "124lb"
        }
    }
}

Maybe thats why you cant convert to an object

Note: I would put this as a comment instead as an answer, but i dont have enought reputation T_T

3
Jon Skeet On

JsonObject.get returns a JsonElement - it might be a string, or a Boolean value etc.

On option is to still call get, but cast to JsonObject:

JsonObject jsonReqPostData = (JsonObject) jsonReqObj.get("postData");

This will fail with an exception if it turns out that postData is a string etc. That's probably fine. It will return null if jsonReqObj doesn't contain a postData property at all - the cast will succeed in that case, leaving the variable jsonReqPostData with a null value.

An alternative option which is probably clearer is to call getAsJsonObject instead:

JsonObject jsonReqPostData = jsonReqObj.getAsJsonObject("postData");