7

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 ?

marknorkin
  • 3,904
  • 10
  • 46
  • 82
  • 1
    May want to take a look at this http://stackoverflow.com/a/15116323/2044733. The second option, beginning "To use JsonObject," looks like exactly what you want. – bbill Jun 08 '15 at 19:15

3 Answers3

11

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
10

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.

Community
  • 1
  • 1
bbill
  • 2,264
  • 1
  • 22
  • 28
-1

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

JoseQ
  • 42
  • 3