I have a multi-platform project with three modules...
# multiplatform
l
I have a multi-platform project with three modules:
commonMain
,
jsMain
, and
jvmMain
. The goal is to share data classes in
commonMain
so that my backend (in
jvmMain
) can serialize them to JSON and send them over the network using Ktor, which is working fine. However, when trying to parse the JSON on the frontend (
jsMain
), I encounter an issue where I have to convert the parsed JSON into a
dynamic
type and then manually reconstruct the data class. This step is necessary to prevent the properties from being
null
. This issue seems similar to https://discuss.kotlinlang.org/t/unable-to-read-properties-from-data-object-in-kotlin-js/26897/2
Copy code
// Code that works
    window.fetch("<http://localhost:8080/>").then { response ->
           response.text()
       }.then { data ->
           val parsed = JSON.parse<Example>(data).asDynamic()
           val example = Example(parsed.i)
           println(example.i)
       }.catch {
           console.error(it)
       }

     // Code that fails
       window.fetch("<http://localhost:8080/>").then { response ->
           response.text()
       }.then { data ->
           val parsed = JSON.parse<Example>(data)
           println(parsed.i)
       }.catch {
           console.error(it)
       }


@Serializable
data class Example(val i: Int)
j
Because you're using JavaScript API to parse the response. Try with this
Json.decodeFromString()
method
1
l
I am trying to avoid having the serialization library on my frontend so I can have a smaller bundle size.
j
Then the dynamic approach needs to be followed
l
Is there no work around? I do not want to manually parse my types.