How to map a JSON string to Kotlin Map
No additional library is needed:
val jsonObj = JSONObject(jsonString)
val map = jsonObj.toMap()
where toMap is:
fun JSONObject.toMap(): Map<String, *> = keys().asSequence().associateWith {
when (val value = this[it])
{
is JSONArray ->
{
val map = (0 until value.length()).associate { Pair(it.toString(), value[it]) }
JSONObject(map).toMap().values.toList()
}
is JSONObject -> value.toMap()
JSONObject.NULL -> null
else -> value
}
}
This can be done with Klaxon. With this you can easily read the Json data as JsonObject
which is actually a MutableMap
.
val json: JsonObject = Parser().parse(jsonData) as JsonObject