【问题标题】:Gson: Not a JSON ObjectGson:不是 JSON 对象
【发布时间】:2015-08-23 09:27:01
【问题描述】:

我将以下字符串传递给服务器:

{
    "productId": "",
    "sellPrice": "",
    "buyPrice": "",
    "quantity": "",
    "bodies": [
        {
            "productId": "1",
            "sellPrice": "5",
            "buyPrice": "2",
            "quantity": "5"
        },
        {
            "productId": "2",
            "sellPrice": "3",
            "buyPrice": "1",
            "quantity": "1"
        }
    ]
}

这是http://jsonlint.com/的有效json

我想获取bodys数组字段。

我就是这样做的:

Gson gson = new Gson();
JsonObject object = gson.toJsonTree(value).getAsJsonObject();
JsonArray jsonBodies = object.get("bodies").getAsJsonArray();

但在第二行,我得到了下面列出的异常:

HTTP Status 500 - Not a JSON Object: "{\"productId\":\"\",\"sellPrice\":\"\",\"buyPrice\":\"\",\"quantity\":\"\",\"bodies\":[{\"productId\":\"1\",\"sellPrice\":\"5\",\"buyPrice\":\"2\",\"quantity\":\"5\"},{\"productId\":\"2\",\"sellPrice\":\"3\",\"buyPrice\":\"1\",\"quantity\":\"1\"}]}"

那该怎么做呢?

【问题讨论】:

标签: java json gson


【解决方案1】:

我之前使用过https://stackoverflow.com/a/15116323/2044733 中描述的parse 方法,并且有效。

实际代码如下所示

JsonParser jsonParser = new JsonParser();
jsonParser.parse(json).getAsJsonObject();

the docs 看来,您遇到了所描述的错误,它认为您的toJsonTree 对象类型不正确。

上面的代码等价于

JsonElement jelem = gson.fromJson(json, JsonElement.class);

如此处的另一个答案和链接线程中所述。

【讨论】:

    【解决方案2】:

    Gson#toJsonTree javadoc 状态

    此方法将指定的对象序列化为它的等价物 表示为JsonElements 的树。

    也就是说,它基本上是这样的

    String jsonRepresentation = gson.toJson(someString);
    JsonElement object = gson.fromJson(jsonRepresentation, JsonElement.class);
    

    Java String 被转换为 JSON 字符串,即。 JsonPrimitive,而不是 JsonObject。换句话说,toJsonTree 将您传递的 String 值的内容解释为 JSON 字符串,而不是 JSON 对象。

    你应该使用

    JsonObject object = gson.fromJson(value, JsonObject.class);
    

    直接将您的String 转换为JsonObject

    【讨论】:

      【解决方案3】:

      那么JsonArray jsonBodies = object.getAsJsonArray("bodies");

      【讨论】:

      • 考虑到getAsJsonObject 上发生的异常情况会发生什么变化?
      猜你喜欢
      • 2021-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-02
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      相关资源
      最近更新 更多