Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a JSON string to Kotlin Map

Tags:

json

kotlin

I have a simple Kotlin program that access a Mongo database and produce a JSON string as below;

"{
     "_id" : { "$oid" : "593440eb7fa580d99d1abe85"} , 
     "name" : "Firstname Secondname" ,
     "reg_number" : "ATC/DCM/1016/230" ,
     "oral" : 11 ,
     "oral_percent" : 73 , 
     "cat_1" : 57 , 
     "cat_2" : 60 , 
     "cat_average" : 59 , 
     "assignment" : 90
}"

How do I map this in Kotlin Map/MutableMap? Is there an API in Kotlin to read JSON and map it to Map/MutableMap?

like image 957
Amani Avatar asked Jul 02 '17 12:07

Amani


People also ask

Can we convert JSON to map?

We can easily convert JSON data into a map because the JSON format is essentially a key-value pair grouping and the map also stores data in key-value pairs. Let's understand how we can use both JACKSON and Gson libraries to convert JSON data into a Map.

How do I read a JSON file in Kotlin?

put assets folder and a JSON file the assets folder. create a data class. use AssetManager to open the File, then get JSON string. use Gson to parse JSON string to Kotlin object.


1 Answers

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
    }
}
like image 82
Arutyun Enfendzhyan Avatar answered Nov 05 '22 16:11

Arutyun Enfendzhyan