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
// 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
jamshedalamqaderi
01/31/2025, 10:40 AM
Because you're using JavaScript API to parse the response. Try with this
Json.decodeFromString()
method
➕ 1
l
Lucas
01/31/2025, 10:50 AM
I am trying to avoid having the serialization library on my frontend so I can have a smaller bundle size.
j
jamshedalamqaderi
01/31/2025, 2:17 PM
Then the dynamic approach needs to be followed
l
Lucas
02/01/2025, 9:08 AM
Is there no work around? I do not want to manually parse my types.