To convert a map to a JSON string in Kotlin, you can use the kotlinx.serialization library. This library provides an easy way to serialize and deserialize Kotlin objects, including maps, to and from JSON strings.
We can convert a map to a JSON string in Kotlin using the kotlinx.serialization library's Json.encodeToString
function.
For example,
build.gradle.kts
file.myMap
with key-value pairs.Json
class.Json.encodeToString
function.println
.import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
fun main() {
// Declare and initialize a map
val myMap = mapOf(
1 to 10,
2 to 20,
3 to 30,
4 to 40,
5 to 50
)
// Create an instance of the Json class
val json = Json
// Convert the map to a JSON string
val jsonString = json.encodeToString(myMap)
// Print the resulting JSON string
println("JSON string from map: $jsonString")
}
JSON string from map: {"1":10,"2":20,"3":30,"4":40,"5":50}
In this tutorial, we learned How to Convert a Map to a JSON String in Kotlin language with well detailed examples.