35

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?

5
  • Possibly related: stackoverflow.com/questions/22285661/…
    – Nivas
    Jun 27, 2016 at 15:01
  • I don't understand. Are you looking to get a String? Then just toJson passing in the LinkedTreeMap. Jun 27, 2016 at 15:16
  • I'm looking to get a JsonObject by hook or by crook, having not found any way to go directly from LinkedTreeMap to JsonObject, I've started looking at String manipulation, as there is a proper way to get a string converted to JsonObject.
    – Bronanaza
    Jun 27, 2016 at 15:26
  • How did you get a LinkedTreeMap to begin with? Just deserialize directly to JsonObject. Jun 27, 2016 at 15:28
  • The LinkedTreeMap is what I get from the "combination of Spring, Java deciding how to cast what it sees, and frameworks I really shouldn't go changing" The first time I have access to the data it is already a LinkedTreeMap, if you can deserialize LinkedTreeMap directly to JsonObject, that would be the answer to the question.
    – Bronanaza
    Jun 27, 2016 at 15:34

1 Answer 1

74

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);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.