Hi,
I currently get the data from/to Java backend into Kotlin JavaScript via simple Ajax call like this:
class Person(name:String, age:Int)
val person = (Person)JSON.parse("{ name: ‘Jan’, age: 12 } ") //json from some ajax rest call
this works fine for simple classes. However I would like to use data classes like:
data class Person(name:String, age:Int)
to be able to use data classes features.
Does JavaScript Kotlin now supports reflection? Or is it in a roadmap? Is anybody using some XML/JSON parser from json/xml/protobuffs into Kotlin data classes?
Thanks,
Jan
Unfortunately there is no standard solution for this yet. I would start from this:
data class Person(val name: String = "", val age: Int = 0)
fun <T : Any> deserialize(json: String, receiver: T): T {
val d: dynamic = receiver
JSON.parse<T>(json) { key, value ->
d[key] = value
d
}
return receiver
}
fun main(args: Array<String>) {
val p = deserialize("{\"name\": \"uuu\", \"age\": 7}", Person())
console.log(p.toString())
}
it does not recursive deserialization so you need to think deeper
UPD
You also better to check browsers compatibility for JSON.parse