简体   繁体   中英

Gson: Not a JSON Object

I have the following String passed to server:

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

which is a valid json for http://jsonlint.com/

I want to get the bodies array field.

That's how I'm doing it:

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

But on the second line I'm getting exception listed below:

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

How to do it properly then ?

Gson#toJsonTree javadoc states

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

That is, it basically does

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

A Java String is converted to a JSON String, ie. a JsonPrimitive , not a JsonObject . In other words, toJsonTree is interpreting the content of the String value you passed as a JSON string, not a JSON object.

You should use

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

directly, to convert your String to a JsonObject .

I have used the parse method as described in https://stackoverflow.com/a/15116323/2044733 before and it's worked.

The actual code would look like

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

From the docs it looks like you're running into the error described where your it thinks your toJsonTree object is not the correct type.

The above code is equivalent to

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

as mentioned in another answer here and on the linked thread.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM