Gson: Not a JSON Object
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.