https://kotlinlang.org logo
#serialization
Title
# serialization
m

Mohit Gurumukhani

08/20/2018, 9:28 PM
I am kinda confused about using Json-Parser on Kotlin-Native to serialize and deserialize a data class. Are there any samples or resources for this?
t

thevery

08/20/2018, 9:32 PM
m

Mohit Gurumukhani

08/20/2018, 9:48 PM
I was looking at https://github.com/ktorio/ktor/tree/master/ktor-client/ktor-client-features/ktor-client-json and they have kind of a wrapper in the common code in KotlinxSerializer.kt and was pretty excited/confused as its also supported in Native
t

thevery

08/20/2018, 10:25 PM
Only JsonReader/Writer supported for native yet
m

Mohit Gurumukhani

08/20/2018, 10:44 PM
I mean that’s kinda what I want? To read json and convert it to data class and vice versa?
t

thevery

08/20/2018, 11:03 PM
JsonReader ==
JsonReader(string).getLong(key)
But you want full data binding:
Copy code
@Serializable
data class Data(val a: Int, @Optional val b: String = "42")

fun main(args: Array<String>) {
    println(JSON.stringify(Data(42))) // {"a": 42, "b": "42"}
    val obj = JSON.parse<Data>("""{"a":42}""") // Data(a=42, b="42")
}
v

Vsevolod Tolstopyatov [JB]

08/22/2018, 8:33 AM
Full data binding in K/N is not yet supported, so you have to write serializers by hand with json builders: https://github.com/Kotlin/kotlinx.serialization/tree/master/json/common/test/kotlinx/serialization/json/examples
3 Views