Fedor Bobin
02/20/2018, 11:57 AM@Serializable
data class Test(var inner: Map<String, String>)
......
try{
val str = """
{
"inner" : {
"a" : "b"
}
}
""".trimIndent()
val parsed = JSON.parse<Test>(str)
parsed.inner.forEach {
println(it)
}
}catch (e: Throwable){
println(e.message)
}
It prints
Cannot read property 'iterator' of undefined
because inner map is deserializable to object (not to Map).
Can you help me?anton.bannykh
02/20/2018, 11:59 AMsandwwraith
02/20/2018, 12:07 PMFedor Bobin
02/20/2018, 12:15 PMFedor Bobin
02/21/2018, 2:30 AMkotlinx.serialization
but from kotlin.core
. May be it should be different names or different method names?sandwwraith
02/21/2018, 8:57 AManton.bannykh
02/21/2018, 10:27 AManton.bannykh
02/21/2018, 11:53 AMexternal interface
declaration. Or just Json
. Or dynamic
. Most importantly, don't use some Kotlin class, since the compiler will assume it has some extra feature (e.g. methods defined on the protype, some metadata, etc), and there will be nothing like that on the actual Json value, created by the javascript JSON.parse function.anton.bannykh
02/21/2018, 11:53 AMimport kotlin.js.*
external interface Test {
val inner: Json
}
private fun Json.toMap(): Map<String, String> {
val map: MutableMap<String, String> = linkedMapOf()
for (key in js("Object").keys(this)) {
map.put(key, this[key] as String)
}
return map
}
fun main(args: Array<String>) {
val str = """
{
"inner" : {
"a" : "b"
}
}
""".trimIndent()
try {
val parsed = JSON.parse<Test>(str)
parsed.inner.toMap().forEach {
println(it)
}
} catch (t: Throwable) {
println(t.message)
}
}
sandwwraith
02/21/2018, 12:09 PMkotlin.js.JSON
auto-import, because it’s a common issue for kotlinx-serialization-js usersanton.bannykh
02/21/2018, 12:21 PMimport kotlinx.serialization.json.JSON
?sandwwraith
02/21/2018, 12:21 PMJSON
, idea auto-imports kotlin.js.JSON
and doesn’t suggest to import kotlinx.serialization.json.JSON
anton.bannykh
02/21/2018, 12:24 PMimport kotlinx.serialization.*
would hide the kotlin.js.JSONanton.bannykh
02/21/2018, 12:25 PMimport
statement in order to use it (which I personally dislike)sandwwraith
02/21/2018, 12:25 PManton.bannykh
02/21/2018, 12:26 PM