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?
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() .
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With