Reputation: 1365
I want to get a JavaScript object loaded into a Kotlin class. As a safety check, I need to verify that the Kotlin object is actually the class I’ve created because some JavaScript code parts are not my design. I need the JavaScript to return correctly, but I cannot verify the Kotlin class.
e.g.
JavaScript object
<script id="myJS">
function MyClass(id, name){
var obj = {};
obj.id = id;
obj.name = name;
return obj;
}
var myClass = MyClass(0, "name_0");
</script>
Kotlin class
class MyClass(
val id: Int,
val name: String
)
I use this Kotlin code to get JavaScript object on Kotlin.
val myJS: dynamic = document.getElementById("myJS")
val myClass: MyClass = JSON.parse<MyClass>(JSON.stringify(myJS.myClass))//get JavaScript object
println(myClass.id)//success output "0"
println(myClass.name)//success output "name_0"
println(myClass is MyClass)//but check class this output "false"
How can I verify the JavaScript object is the created Kotlin class?
Upvotes: 2
Views: 2666
Reputation: 23
Use serialization
@Serializable
data class MyClass(val id: Int, val name: String)
Json.decodeFromString(MyClass.serializer(), JSON.stringify(js("{}")))
Upvotes: 0
Reputation: 259
This might be helpful:
class MyClass(val id: Int, val name: String) {
constructor(obj: dynamic): this(obj.id, obj.name)
override fun toString(): String =
"${this.id} ${this.name}"
}
fun main() {
val obj = js("{}")
obj.id = 1
obj.name = "Mike"
val myObj = MyClass(obj)
println(myObj)
println(myObj is MyClass)
}
Upvotes: 0
Reputation: 395
Use JSON.parse
from kotlinx.serialization library instead of JSON.parse
from Kotlin/JS standard library.
JSON from Kotlin standard library is just a view around JavaScript JSON object . So JSON.parse
creates regular JS object without any information about Kotlin type.
Its fine to use it with external classes that can't be type-checked. But your MyClass
is a regular class.
Objects constructed from regular Kotlin classes have special metadata which is essential for type checks myClass is MyClass
and reflection myClass::class == MyClass::class
. And kotlinx.serialization library creates these full-featured Kotlin objects.
Upvotes: 2