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 ?
The JSON format was originally specified by Douglas Crockford. On the other hand, GSON is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.
GSON can use the Object definition to directly create an object of the desired type. While JSONObject needs to be parsed manually.
Gson can work with arbitrary Java objects including objects for which you do not have the source. For this purpose, Gson provides several built in serializers and deserializers. A serializer allows to convert a Json string to corresponding Java type. A deserializers allows to convert from Java to a JSON representation.
public final class JsonObject extends JsonElement. A class representing an object type in Json. An object consists of name-value pairs where names are strings, and values are any other type of JsonElement. This allows for a creating a tree of JsonElements.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With