gpt4 book ai didi

kotlin - 使用 Gson 序列化 Kotlin 委托(delegate)

转载 作者:行者123 更新时间:2023-12-02 11:33:47 24 4
gpt4 key购买 nike

我有一个 Kotlin 对象,正在尝试使用 Gson 序列化。设置为委托(delegate)的成员不会被序列化。如果我直接调用它,委托(delegate)就会起作用,就像 onChange 回调一样,但 Gson 会忽略它。

有什么方法可以让 Gson 在不编写自定义序列化器的情况下对其进行序列化吗?

这是我正在尝试做的事情的简化示例:

class MyDelegate() {

fun getProperty(): String {
return "myDelegate Property"
}

fun observableDelegate(onChange: () -> Unit): ReadWriteProperty<Any?, String> {

return object: ReadWriteProperty<Any?, String> {
override fun getValue(thisRef: Any?, property: KProperty<*>): String {
return getProperty()
}

override fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
TODO("not implemented")
}
}
}
}

class MyTest(delegate: MyDelegate, val property0: String = "property0" ) {

val property1 = "property1"
var property2 = "property2"
var property3: String by delegate.observableDelegate {
// onChange called
}
}

测试它:

@Test
fun testDelegate() {

val t1 = MyTest(MyDelegate())
val s1 = Gson().toJson(t1)

Assert.fail(s1)

}

输出:

{"property1":"property1","property2":"property2","property0":"property0"}

最佳答案

property3 变量不受字段支持。因此,Gson 不会将其视为 Json 序列化中的字段。

GsonDesignDocument属性的状态

Some Json libraries use the getters of a type to deduce the Json elements. We chose to use all fields (up the inheritance hierarchy) that are not transient, static, or synthetic. We did this because not all classes are written with suitably named getters. Moreover, getXXX or isXXX might be semantic rather than indicating properties.

因此,您可能必须根据需要实现自定义(反)序列化器。

关于kotlin - 使用 Gson 序列化 Kotlin 委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49365413/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com