Gson:不是 JSON 对象

Gson: 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"
        }
    ]
}

这是 http://jsonlint.com/

的有效 json

我想获取 bodies 数组字段。

我就是这样做的:

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\"}]}"

那怎么办才好呢?

我之前使用过中描述的parse方法并且有效。

实际代码看起来像

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

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

以上代码等同于

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

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

Gson#toJsonTree javadoc 状态

This method serializes the specified object into its equivalent representation as a tree of JsonElements.

也就是说,基本上是这样

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

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

你应该使用

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

直接将您的 String 转换为 JsonObject

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