Gson:不是JSON对象

mar*_*kin 6 java json gson

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

{
    "productId": "",
    "sellPrice": "",
    "buyPrice": "",
    "quantity": "",
    "bodies": [
        {
            "productId": "1",
            "sellPrice": "5",
            "buyPrice": "2",
            "quantity": "5"
        },
        {
            "productId": "2",
            "sellPrice": "3",
            "buyPrice": "1",
            "quantity": "1"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

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

我想获取body数组字段.

我就是这样做的:

Gson gson = new Gson();
JsonObject object = gson.toJsonTree(value).getAsJsonObject();
JsonArray jsonBodies = object.get("bodies").getAsJsonArray();
Run Code Online (Sandbox Code Playgroud)

但在第二行我得到的例外情况如下:

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\"}]}"
Run Code Online (Sandbox Code Playgroud)

那怎么做呢?

Sot*_*lis 10

Gson#toJsonTree贾瓦多克

此方法将指定对象序列化为其等效表示形式为JsonElements 树.

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

String jsonRepresentation = gson.toJson(someString);
JsonElement object = gson.fromJson(jsonRepresentation, JsonElement.class);
Run Code Online (Sandbox Code Playgroud)

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

你应该用

JsonObject object = gson.fromJson(value, JsonObject.class);
Run Code Online (Sandbox Code Playgroud)

直接,将你转换StringJsonObject.


bbi*_*ill 9

之前我已经使用了/sf/answers/1058142641/中parse描述的方法并且它已经工作了.

实际代码看起来像

JsonParser jsonParser = new JsonParser();
jsonParser.parse(json).getAsJsonObject();
Run Code Online (Sandbox Code Playgroud)

文档中看起来你正在遇到所描述的错误,它认为你的toJsonTree对象不是正确的类型.

上面的代码相当于

JsonObject jelem = gson.fromJson(json, JsonElement.class);
Run Code Online (Sandbox Code Playgroud)

正如在这里的另一个答案和链接的线程中提到的那样.