I have HashMap in Kotlin
val map = HashMap<String, String>()
map.put("key1","value1");
map.put("key2","value2");
map.put("key3","value3");
How to convert it into String in JSON format? like
{"key1": "value1", "key2": "value2", "key3": "value3"}
By using new Gson(). By creating a GsonBuilder instance and calling with the create() method.
A JSONObject is an unordered collection of name/value pairs whereas Map is an object that maps keys to values. A Map cannot contain duplicate keys and each key can map to at most one value. We need to use the JSON-lib library for serializing and de-serializing a Map in JSON format.
A Hash is a sparse array that uses arbitrary strings/objects (depending on the implementation, this varies across programming languages) rather than plain integers as keys. In Javascript, any Object is technically a hash (also referred to as a Dictionary, Associative-Array, etc).
You can use org.json
which is shipped with Android:
JSONObject(map).toString()
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