Hi again, is there an easy way to convert Kotlin d...
# javascript
f
Hi again, is there an easy way to convert Kotlin data classes (or normal classes) to JS objects? I have tried the
Any.asJsObject()
functions but that doesn't seem to do the trick. My use case is that I'm trying to use the Firestore JS library to save some data but it only receives JS objects as input when trying to save data and I'm using normal Kotlin classes to handle this same data in the we app logic.
t
Do you use
kotlinx-serialization
?
f
I do use it @turansky, but I didn't find a way to convert Kotlin classes to JS object there, only the opposite. Did I miss it somewhere?
t
kotlinx-serialization
include both serialization & deserialization
JSON -> Kotlin Class Kotlin Class -> JSON
Also supportted: JS Object -> Kotlin Class (
DynamicJbjectParser
)
f
Yes but what I need is Kotlin class to JS Object
that is not covered in the stuff you mentioned above, JSON is not the same as JS Object as far as I understand (although I might be wrong as I'm pretty new to JS)
t
Untitled.kt
f
That doesn't seem to compile, I tried it in the Kotlin Playground and I got the error:
Copy code
Type inference failed: Not enough information to infer parameter T in fun <T> parse(text: String): T Please specify it explicitly.
then I tried setting the value of T like this:
Copy code
val jsObject = JSON.parse<JsObject>(jsonString)
and it failed with this error:
Copy code
Uncaught SyntaxError: Unexpected token a in JSON at position 2
Did you try that code and it worked for you?
t
f
Oh cool, seems like setting the type to
dynamic
did the trick, thanks! 🙂