-2

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. 
AshH
  • 39
  • 7
  • 1
    As a side-note, it would have been useful to show *where* you got the error. Given that (I assume) it's on the line with the call to `get`, everything else (in particular the `save` method) is irrelevant. – Jon Skeet Apr 22 '21 at 06:06

2 Answers2

1

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");
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

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