我是 Kotlin 的新手,甚至是 Kotlin Serialization 的新手我正在尝试将 Kotlin 数据类转换为 JSON。看下面的示例代码:
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JSON
fun main(args: Array<String>) {
println(JSON.stringify(BaseClass1("abc")))
println(JSON.stringify(BaseClass2("abc")))
}
@Serializable
data class BaseClass1(
val a: String
)
@Serializable
data class BaseClass2(
val a: Any
)
输出是:
{"a":"abc"}
{"a":["kotlin.String","abc"]}
所以我将一个字符串保存在类型为
Any
的变量中(这应该是完全有效的)。但是,这会导致序列化值成为类型和值的数组。其他类和子类也会发生这种情况(例如,当我扩展字段的类型时)。我怎样才能得到
stringify
无论字段的实际类型如何,始终使用该值?我想要第二个 stringify
上面程序的结果与第一个匹配。
最佳答案
我设法使用自定义序列化程序来完成此操作。
唯一的缺点是因为我不保存类型,所以我不能再次反序列化对象,但我只需要在我的程序中进行序列化。
@Serializable
data class BaseClass2(
@Serializable(with = PlainObjectSerializer::class) val a: Any
)
object PlainObjectSerializer : KSerializer<Any> {
override val serialClassDesc: KSerialClassDesc
get() = SerialClassDescImpl("") //PlainObjectDesc
override fun save(output: KOutput, obj: Any) {
val saver = serializerByValue(obj, output.context)
output.writeSerializableValue(saver, obj)
}
override fun load(input: KInput): Any {
throw Exception("This serializer can only be used for serialization!")
}
}
编辑:作为@ Nikky suggested ,可以通过使用序列化插件进一步简化此代码:
@Serializer(forClass = BaseClass2::class)
object PlainObjectSerializer : KSerializer<Any> {
override fun save(output: KOutput, obj: Any) {
val saver = serializerByValue(obj, output.context)
output.writeSerializableValue(saver, obj)
}
}
关于json - Kotlin 序列化为 JSON : How to ignore actual field type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52316671/