munish
munish

Reputation: 485

How to convert HashMap to JsonObject directly

I checked that I can convert the hashmap to json using Gson, but it's giving String. Then I've to convert this string to JsonObject.

Is there any way that I can convert the hashmap to JsonObject directly using gson

Upvotes: 2

Views: 9161

Answers (1)

Jimi Kimble
Jimi Kimble

Reputation: 504

Gson gson = new Gson();
gson.toJsonTree(hashmap).getAsJsonObject();

This is what I was able to glean from reading the API It seems to me you want to use the .toJsonTree method instead of the .toJson method and then get the JsonElement as a JsonObject

Upvotes: 14

Related Questions