我按照教程为我的泛型类创建了自定义序列化。但我仍然有错误:
SerializationException:找不到类“ApiResponse”的序列化程序。将类标记为 @Serializable 或显式提供序列化程序。
我的 ApiResponse 类如下所示:
@Serializable(with = ApiResponseSerializer::class)
class ApiResponse<T>(
@SerialName("data")
val data: T? = null,
@SerialName("error")
val error: ApiError? = null
)
上面注释中使用的 ApiResponseSerializer 是:
class ApiResponseSerializer<T>(private val dataSerializer: KSerializer<T>) : KSerializer<ApiResponse<T>> {
override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ApiResponseDataSerializer") {
val dataDescriptor = dataSerializer.descriptor
element("data", dataDescriptor)
element("error", ApiError.serializer().descriptor)
}
override fun deserialize(decoder: Decoder): ApiResponse<T> =
decoder.decodeStructure(descriptor) {
var data: T? = null
var error: ApiError? = null
loop@ while (true) {
when (val i = decodeElementIndex(descriptor)) {
0 -> data = decodeSerializableElement(descriptor, i, dataSerializer)
1 -> error = decodeSerializableElement(descriptor, i, ApiError.serializer())
CompositeDecoder.DECODE_DONE -> break
else -> throw SerializationException("Unknown index $i")
}
}
ApiResponse(data, error)
}
override fun serialize(encoder: Encoder, value: ApiResponse<T>) {
encoder.encodeStructure(descriptor) {
encodeNullableSerializableElement(descriptor, 0, dataSerializer, value.data)
encodeNullableSerializableElement(descriptor, 1, ApiError.serializer(), value.error)
}
}
}
然后,当我尝试序列化我的数据对象时,我收到了上面提到的异常。
Json.encodeToString(ApiResponse(data = response.data))
---- OR ----
Json.encodeToString(ApiResponse.serializer(T::class.serializer()), ApiResponse(data = response.data))
有人能告诉我哪里错了吗?谢谢你。