Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a LinkedTreeMap to gson JsonObject

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?

like image 784
Bronanaza Avatar asked Jun 27 '16 14:06

Bronanaza


People also ask

How to convert JSON string to map in Java using gson?

When we call the fromJson API on this Gson object, the parser invokes the custom deserializer and returns the desired Map instance: String jsonString = "{'Bob': '2017-06-01', 'Jennie':'2015-01-03'}"; Type type = new TypeToken<Map<String, Date>>(){}. getType(); Gson gson = new GsonBuilder() .

Can we convert JSONObject to string?

Stringify a JavaScript Objectstringify() to convert it into a string. const myJSON = JSON. stringify(obj); The result will be a string following the JSON notation.

What is LinkedTreeMap Java?

Class LinkedTreeMap<K,V>A map of comparable keys to values. Unlike TreeMap , this class uses insertion order for iteration order. Comparison order is only used as an optimization for efficient insertion and removal. This implementation was derived from Android 4.1's TreeMap class.


1 Answers

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); 
like image 109
Sotirios Delimanolis Avatar answered Sep 23 '22 04:09

Sotirios Delimanolis