Alex Styl
05/07/2024, 7:19 AMArtem Kobzar
05/07/2024, 7:22 AMkotlinx.serialization
is the Kotlin way to work with JSON. But it's slow on JS 😓Alex Styl
05/07/2024, 7:30 AMJson.decodeFromString<Project>(string)
it needs a type. what would the type be?CLOVIS
05/07/2024, 7:30 AMJSON.stringify
is relatively safe, it's JSON.parse
that dangerousAlex Styl
05/07/2024, 7:34 AM// .kt
fun kotlinCode(): Any {
val arrayWithDataClasses = ...
return JSON.stringify(arrayWithDataClasses)
}
and then from nodejs
val string = KotlinModule.kotlinCode()
val obj = JSON.parse(string)
but the objects look like:
{
l2_1 : "key",
m2_1 : "value
}
instead of
{
"key": "value"
}
CLOVIS
05/07/2024, 7:43 AM@JsExport
help?CLOVIS
05/07/2024, 7:44 AMJSON.parse
on it? That's a bit expensive of a roundtrip 😕 And also, objects created from JSON.parse
can't be safely passed back to Kotlin down the line, so be wary of thatAlex Styl
05/07/2024, 7:52 AMfun <E> List<E>.toJsonArray(): List<dynamic> {
val array: dynamic = js("([])")
this.forEach {
array.push(it)
}
return array
}
fun buildJsonObject(builder: MutableMap<String, dynamic>.() -> Unit): Any {
val jsObject: dynamic = js("({})")
val map = mutableMapOf<String, dynamic>()
map.apply(builder)
map.forEach { (key, value) ->
jsObject[key] = value
}
return jsObject
}
CLOVIS
05/07/2024, 7:59 AMAlex Styl
05/07/2024, 8:04 AMCLOVIS
05/07/2024, 8:05 AMAlex Styl
05/07/2024, 8:06 AMCLOVIS
05/07/2024, 8:07 AMandylamax
05/07/2024, 10:58 AMEdoardo Luppi
05/07/2024, 11:41 AMBut it's slow on JSI need to find the benchmarks I had looked at, because perf had gotten way better over time
Edoardo Luppi
05/07/2024, 11:44 AMAyfri
05/07/2024, 12:05 PM@JSPlainObject
https://kotlinlang.org/docs/whatsnew-eap.html#support-for-type-safe-plain-javascript-objects
Then you'll be able to just use JSON.stringify
and JSON.parse
without having mangled fieldsEdoardo Luppi
05/07/2024, 12:08 PMJsPlainObject
works only on externals and it basically adds a constructor to the interface declaration. So not much different to what you'd do now with jso { }
.Ayfri
05/07/2024, 12:08 PMEdoardo Luppi
05/07/2024, 12:09 PMAyfri
05/07/2024, 12:19 PMprashan
05/07/2024, 4:17 PMArtem Kobzar
05/08/2024, 9:10 AM