android - 如何序列化自定义类型的 ArrayList?
问题描述
我和这个成员一起上课:
var wpts : ArrayList<Location>
我还创建了一个自定义序列化程序:
object LocationSerializer: KSerializer<Location>{
override val descriptor = buildClassSerialDescriptor("Location") {
element<Double>("lat")
element<Double>("lon")
}
override fun deserialize(decoder: Decoder): Location = decoder.decodeStructure(descriptor) {
var lat = -1.0
var lon = -1.0
while (true) {
when (val index = decodeElementIndex(descriptor)) {
0 -> lat = decodeDoubleElement(descriptor, 0)
1 -> lon = decodeDoubleElement(descriptor, 1)
CompositeDecoder.DECODE_DONE -> break
else -> error("Unexpected index: $index")
}
}
require(lat in -90.0..90.0 && lon in -180.0..180.0)
val l = Location("")
l.latitude = lat
l.longitude = lon
return l
}
override fun serialize(encoder: Encoder, value: Location) = encoder.encodeStructure(descriptor) {
encodeDoubleElement(descriptor, 0, (value.latitude))
encodeDoubleElement(descriptor, 1, (value.longitude))
}
}
我不知道如何为wpts成员定义序列化程序,并且添加此注释不起作用:
@Serializable(with = Serializers.Companion.LocationSerializer::class)
我不断收到此错误:
未找到“位置”类型的序列化程序。
解决方案
假设您在谈论android.location.Location
,我只看到以下选项:
创建您自己的可序列化 Location 类并使用它来代替:
@Serializable(with = MyLocationSerializer::class) class MyLocation(provider: String): Location(provider)
和
var wpts : ArrayList<MyLocation>
为
ArrayList<Location>
.使用 Gson 或其他序列化库。
推荐阅读
- visual-studio - Nunit 单元测试中没有命中断点
- javascript - HTML 选择选项列表中的偏移文本
- matlab - 如何从 Matlab 中的数据集中提取 LBP 特征?
- c - 如何在不使用 C 中的数组的情况下读取给定的“n”输入?
- android - Android Studio在退出时杀死ADB服务器
- go - 使用 -race 标志时,GO 中的竞态条件是什么意思
- javascript - 编写一个更新/保存的 Mongoose 方法?
- c# - Xamarin Forms - 异步任务“EventHandler 的签名(返回类型)与事件类型不匹配”
- c# - 将 vb6“类型”(结构)转换为 c# 的最佳方法
- javascript - Mobx 强制计算值更新