To convert a JSON string to a map in Kotlin, you can use the kotlinx.serialization library, which provides functions to parse JSON data and convert it into a map.
We can convert a JSON string to a map in Kotlin by using the kotlinx.serialization library's Json.decodeFromString function to parse the JSON string and convert it into a map.
For example,
Json.decodeFromString
function to parse the JSON string into a map.import kotlinx.serialization.json.Json
import kotlinx.serialization.decodeFromString
fun main() {
// Define a JSON string
val jsonString = "{\"1\": 10, \"2\": 20, \"3\": 30, \"4\": 40, \"5\": 50}"
// Parse the JSON string into a map
val myMap: Map<String, Int> = Json.decodeFromString(jsonString)
// Print the resulting map
println("Map from JSON string:")
for ((key, value) in myMap) {
println("$key: $value")
}
}
Map from JSON string: 1: 10 2: 20 3: 30 4: 40 5: 50
In this tutorial, we learned How to Convert a JSON String to a Map in Kotlin language with well detailed examples.