I use kotlin on javascript platform. This code fails on the sixth line with exception "Uncaught TypeError: a.c.iterator is not a function".
class A(val b: String, val c: List<String>)
fun main(args: Array<String>) {
val a = JSON.parse<A>("""{"b": "b_value", "c": ["c_value_1", "c_value_2"]}""")
println(a.b)
for (c in a.c) println(c)
}
In javascript debuger I can see, that object "a" is deserialized. But I think, it is not a valid kotlin object of type A. Is any way, how to create valid kotlin object instance of type A from the object "a" or from original json string?
You should not use JSON.parse
with regular Kotlin classes. Use it with external interfaces instead, i.e.:
external interface A(val b: String, val c: Array<String>)
fun main(args: Array<String>) {
val a = JSON.parse<A>("""{"b": "b_value", "c": ["c_value_1", "c_value_2"]}""")
println(a.b)
for (c in a.c) println(c)
}
Sorry, such restriction can't be expressed via Kotlin type system.
And yes, as @marstran mentioned, you should not use List<T>
and other Kotlin collections in this case. We are working on a library for deserializing JSON to Kotlin JS classes (similar to Jackson in JVM), but I can't say anything about the timeframe yet.
UPD: there's kotlinx.serialization library which maps Kotlin classes to and from JSON.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With