How to convert HashMap to JSON in Kotlin
Solution 1
You can use org.json
which is shipped with Android:
JSONObject(map).toString()
Solution 2
You can use Gson for that,
Here is the example,
val map = HashMap<String, String>()
map.put("key1","value1");
map.put("key2","value2");
map.put("key3","value3");
val gson = Gson()
Log.d("TAG", gson.toJson(map).toString())
and the oputput is,
{"key1":"value1","key2":"value2","key3":"value3"}
Solution 3
If someone has problems in Koltlin, you can use gson like this:
val gson = Gson()
val json = JSONObject(gson.toJson(map))
Solution 4
import kotlinx.serialization.*
import kotlinx.serialization.json.*
fun main() {
var store = HashMap<String, String>()
var jsonString= Json.encodeToString(store)
var anotherStore = Json.decodeFromString(jsonString)
}
![Asad Ali Choudhry](https://i.stack.imgur.com/VbsOs.jpg?s=256&g=1)
Asad Ali Choudhry
I have more than 5 years of experience in creating complex native mobile applications for iPhone and Android. I am adept in analyzing information, requirements, and system needs, evaluating end-user requirements, and developing solutions according to the needs. I am working in Dubai for the last 1.5 years and got diverse experience in development and team-leading. I can also work independently and can manage complex and big projects. I am also the co-founder of the website https://handyopinion.com/ where we share complex coding solutions with the young developers.
Updated on May 29, 2021Comments
-
Asad Ali Choudhry about 3 years
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"}
-
Milan Pansuriya about 5 yearsuse Gson to convert Hashmap to Json
-
-
Zulqurnain Jutt over 2 yearsWhat about string to map ?
-
Miha_x64 over 2 years@ZulqurnainJutt, do you mean a string with a JSON object inside, i.e. backwards conversion?