如何使用 Jackson/kotlinx.serialization 将 json 反序列化为 Kotlin 中的泛型类型

How to deserialize json to generic type in Kotlin using Jackson/kotlinx.serialization

我有一个泛型 class class MyClass<T> : MyInterface<T>,我想将 json 反序列化为泛型类型 T。我尝试使用 Jackson 和 kotlinx.serialization 库反序列化 json 但出现以下错误

cannot use T as reified type parameter. Use class instead.

我对发生这种情况的理解是因为 Jackson 和 kotlinx 反序列化函数都期望具体化 T 但在我的 class 中没有办法在编译时知道 T 的类型。我对这个错误的理解是否正确?有什么办法可以解决这个错误吗?

我的代码片段

class MyClass<T> : MyInterface<T>{
    .... <some code> ...
    
    fun readFromJson(json: String){
        val obj = jacksonObjectMapper().readValue<T>(json)
        // same error if I use kotlinx Json.decodeFromString<T>(json)
        ...
    }
    .... <some code> ...
}

My understanding of why this is happening is because both Jackson and kotlinx deserialize function expect reified T but in my class there is no way to know the type of T at compile time. Is my understanding of this error correct?

正确。

Is there any way to resolve this error?

这取决于您要对相关 T 执行的操作。最好的办法是将 readFromJson() 从 class 提升到 T 可以实际具体化的地方。

如果你真的需要这个函数出现在你的 class 中(例如你需要访问一些内部状态或其他东西),那么你必须传递一个 KClass<T>/Class<T>(对于 Jackson)或 DeserializationStrategy<T>(对于 Kotlinx 序列化)到您的 class 的构造函数,以便您可以使用 readValue() 或 [= 的非具体化重载20=] 将此额外信息作为参数。