does Kotlin Serialization support delegated proper...
# serialization
j
does Kotlin Serialization support delegated properties or will i need to implement a custom serializer for that?
Copy code
@Serializable
class Test {

    var firstName: String by Delegates.observable(
        initialValue = "Someone",
        onChange = { _, _, _ ->
            println("firstName changed")
        }
    )

}
Copy code
val json = Json(JsonConfiguration.Stable)
    val test = Test()
    test.firstName = "Person"
    val jstring = json.toJson(Test.serializer(), test)
    println(jstring.toString())
ouputs:
{}
Seems i'll need to do something like this
Copy code
private var firstNameField: String = ""

    var firstName: String by Delegates.observable(
        initialValue = firstNameField,
        onChange = {_, _, newValue ->
            this.firstNameField = newValue
        }
    )
The generated json will then just contain some boilerplate which is not the end of the world
Copy code
{
  "firstNameField": "Person"
}
custom serializer works even better, maybe somewhat verbose, but that's fine
Copy code
@Serializable
class Test {

    var firstName: String by Delegates.observable(
        initialValue = "Firstname",
        onChange = { _, _, newValue ->
            println("firstname changed")
        }
    )

    var lastName: String by Delegates.observable(
        initialValue = "Lastname",
        onChange = { _, _, newValue ->
            println("lastname changed")
        }
    )

    @Serializer(forClass = Test::class)
    companion object : KSerializer<Test> {
        override val descriptor: SerialDescriptor
            get() = PrimitiveDescriptor("MyData", PrimitiveKind.STRING)

        @ImplicitReflectionSerializer
        override fun serialize(encoder: Encoder, value: Test) {
            val map = mapOf(
                "firstName" to value.firstName,
                "lastName" to value.lastName
            )
            encoder.encode(map)
        }
    }

}