marknorkin
marknorkin

Reputation: 4084

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 ?

Upvotes: 7

Views: 31570

Answers (3)

bbill
bbill

Reputation: 2304

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.

Upvotes: 10

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280177

Gson#toJsonTree javadoc states

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

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.

Upvotes: 11

JoseQ
JoseQ

Reputation: 42

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

Upvotes: -1

Related Questions