How do I convert a LinkedTreeMap to gson JsonObject

25,129

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);
Share:
25,129
Bronanaza
Author by

Bronanaza

Updated on June 28, 2020

Comments

  • Bronanaza
    Bronanaza almost 4 years

    For a java data handler, I send properly formatted JSON, but a combination of Spring, Java deciding how to cast what it sees, and frameworks I really shouldn't go changing mangle that JSON so that once I can see it, it's turned into a LinkedTreeMap, and I need to transform it into a JsonObject. This is not to serialize/de-serialize JSON into java objects, it's "final form" is a gson JsonObject, and it needs to be able to handle literally any valid JSON.

    {
    "key":"value",
    "object": {
        "array":[
            "value1", 
            "please work"
            ]
        }
    }
    

    is the sample I've been using, once I see it, it's a LinkedTreeMap that .toString() s to

    {key=value, object={array=[value1, please work]}}
    

    where you can replace "=" with ":", but that doesn't have the internal quotes for the

    new JsonParser().parse(gson.toJson(STRING)).getAsJsonObject()
    

    strategy.

    Is there a more direct way to convert LinkedTreeMap to JsonObject, or a library to add the internal quotes to the string, or even a way to turn a sting into a JsonObject that doesn't need the internal quotes?