Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin JS JSON deserialization

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?

like image 904
user3706629 Avatar asked Jun 23 '17 07:06

user3706629


1 Answers

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.

like image 61
Alexey Andreev Avatar answered Sep 18 '22 09:09

Alexey Andreev