How to convert HashMap to JSON in Kotlin

Viewed 25164

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"}
5 Answers

You can use org.json which is shipped with Android:

JSONObject(map).toString()

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"}

Use kotlinx.serialization:

import kotlinx.serialization.*
import kotlinx.serialization.json.*

fun main() {
   var store = HashMap<String, String>()
   var jsonString= Json.encodeToString(store)
   var anotherStore = Json.decodeFromString(jsonString)
}

If someone has problems in Koltlin, you can use gson like this:

val gson = Gson()
val json = JSONObject(gson.toJson(map))

If you are using klaxon, then it would simply be:

val json = Klaxon().toJsonString(map)
Related