How do I convert a LinkedTreeMap to gson JsonObject

You’d typically have to serialize the object to JSON, then parse that JSON back into a JsonObject. Fortunately, Gson provides a toJsonTree method that kind of skips the parsing.

LinkedTreeMap<?,?> yourMap = ...;
JsonObject jsonObject = gson.toJsonTree(yourMap).getAsJsonObject();

Note that, if you can, just deserialize the JSON directly to a JsonObject with

gson.fromJson(theJson, JsonObject.class);

Leave a Comment