JsonElement 上的错误无法转换为 JsonObject

问题描述

所以有一个jsonReqObj,

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

还有一个返回字符串的保存函数。我想用那个save函数,但是save 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 - 它可能是一个字符串,或一个布尔值等。

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

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

如果结果 postData is 是一个字符串等等,这将失败并抛出异常。这可能没问题。如果 null 根本不包含 jsonReqObj 属性,它将返回 postData - 在这种情况下,转换将成功,将变量 jsonReqPostData 保留为空值。

另一种可能更清晰的选项是调用 getAsJsonObject

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

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

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

应该是:

{
    "postData": {
        "name": "abc","weight": "124lb"
        }
    }
}

也许这就是你不能转换为对象的原因

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