Iterating over Json properties


#1

Hi there!

I’m unsuccessfully trying to find a way to iterate over a Json object (which is expected to only contain properties with String values) so that I can fill a Map<String,String> from it. In either way I end up with an illegal cast exception.

Does anyone know how to do this?

Jørund


#2

Could you please show the code that you’re using?


#3

Thanks for following up!

This is what we have tried:

private fun jsonToMap(json: Json): Map<String, String> {
    val map: MutableMap<String, String> = linkedMapOf()
    for (key in json) {
        map.put(key, json[key] as String)
    }

    // or 
    for( (name, value) in json ) {
        map.put(name, value as String)
    }
    return map
}

#4

Hi, @jvskriubakken, try this:

private fun jsonToMap(json: Json): Map<String, String> {
    val map: MutableMap<String, String> = linkedMapOf()
    for (key in js("Object").keys(json)) {
        map.put(key, json[key] as String)
    }
    return map
}

#5

Thanks! It worked!


#6

#7