Kotlin 序列化中的泛型产生编译时错误

Generics in Kotlin Serialization produces compile time error

我在编译同样是通用的序列化数据 class 时遇到问题。我是 Android 和 Kotlin 的新手,但我是一名经验丰富的 iOS/Swift 开发人员(不要反对我)。

我正在尝试围绕 GraphQL 响应设置一个通用数据 class 包装器,它可以 return 我要么是数据字段中的 T 通用,要么是错误字段中的错误。

import kotlinx.serialization.Serializable

@Serializable
data class GraphQLResponse<T:Serializable> (
    val errors : List<ErrorResponse>? = null,
    val data : Map<String, T>? = null
) {
    @Serializable
    data class Location(
        val line: Int? = 0,
        val column: Int? = 0,
        val sourceName: String? = null
    )

    @Serializable
    data class ErrorResponse(
        val locations: List<Location>? = null,
        val errorType: String? = null,
        val message: String? = null
    )
}

编译我得到以下错误:

java.lang.AssertionError: Couldn't load KotlinClass from /Users/brett/Development/Company/android/app/build/tmp/kotlin-classes/debug/com/company/company/network/GraphQLResponse.class; it may happen because class doesn't have valid Kotlin annotations

还有一堆关于反射的警告。

我想用泛型和序列化做的事情是否可行?我需要编写自己的反序列化方法吗?

如有任何帮助和建议,我们将不胜感激。

您需要为类型 T 提供自定义序列化程序。 检查这个 guide (顺便说一句,在你的代码中类型 T 不应该是可序列化的 - T:Serializable。它只是注释)

有类似问题,查看this。 但是,如您所见,即使您提供了序列化程序,如果您在项目中使用 kapt,它也可能无法正常工作。

我从序列化存储库中找到了这个 comment :

However, due to the mentioned kapt issue, it's impossible for now. Probably, a viable workaround can be to move models and serializers to the separate Gradle module, which is not processed by kapt.

关于这个问题还有更多问题: