首页 > 解决方案 > 如何序列化自定义类型的 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)

我不断收到此错误:

未找到“位置”类型的序列化程序。

标签: androidkotlinserialization

解决方案


假设您在谈论android.location.Location,我只看到以下选项:

  1. 创建您自己的可序列化 Location 类并使用它来代替:

    @Serializable(with = MyLocationSerializer::class)
    class MyLocation(provider: String): Location(provider)
    

    var wpts : ArrayList<MyLocation>
    
  2. ArrayList<Location>.

  3. 使用 Gson 或其他序列化库。


推荐阅读