JsonElement上的错误无法转换为JsonObject



因此存在一个jsonReqObj,

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

还有一个保存函数,它将返回一个字符串。我想使用保存函数,但保存json的输入参数应该是postData中的json。

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

下面是我的代码

JsonObject jsonReqPostData = jsonReqObj.get("postData")
String finalMes = save(jsonReqPostData);

但我得到的错误

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

JsonObject.get返回一个JsonElement-它可能是字符串或布尔值等。

选项是仍然调用get,但转换为JsonObject:

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

如果postData是字符串等,这将失败,并出现异常。这可能很好。如果jsonReqObj根本不包含postData属性,它将返回null——在这种情况下,强制转换将成功,使变量jsonReqPostData为null值。

另一种可能更清楚的选择是调用getAsJsonObject

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

我已经用验证了您的JSON文件https://jsonlint.com/看起来格式不正确,而不是:

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

应为:

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

也许这就是为什么你不能转换为对象

注意:我会把这作为一个评论,而不是一个答案,但我没有足够的声誉T_T

最新更新