How to convert HashMap to JSON in Kotlin

21,052

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

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

Share:
21,052
Asad Ali Choudhry
Author by

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, 2021

Comments

  • Asad Ali Choudhry
    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
      Milan Pansuriya about 5 years
      use Gson to convert Hashmap to Json
  • Zulqurnain Jutt
    Zulqurnain Jutt over 2 years
    What about string to map ?
  • Miha_x64
    Miha_x64 over 2 years
    @ZulqurnainJutt, do you mean a string with a JSON object inside, i.e. backwards conversion?