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.
JsonObject.getreturns aJsonElement- it might be a string, or a Boolean value etc.On option is to still call
get, but cast toJsonObject:This will fail with an exception if it turns out that
postDatais a string etc. That's probably fine. It will returnnullifjsonReqObjdoesn't contain apostDataproperty at all - the cast will succeed in that case, leaving the variablejsonReqPostDatawith a null value.An alternative option which is probably clearer is to call
getAsJsonObjectinstead: