我有一个使用Moshi 1.8.0序列化/反序列化数据的工作代码

Upgrading to 1.9.1 now leads to a crash when attempting to serialize:

JAVAlang.IllegalArgumentException:无法序列化Kotlin类型

Here is the serializer code:

val moshi = Moshi.Builder().build()
val dataListType = newParameterizedType(List::class.java, T::class.java)
val adapter: JsonAdapter<List<T>> = moshi.adapter(dataListType)
val json = adapter.toJson(dataList)

对应的T类是

@IgnoreExtraProperties
data class Spot(
    var id: String = "",
    var localizedName: String? = null,
    var type: String = "",
    var location: Location? = null
)

我完全不知道在这里该做些什么.

Thanks for the help!

推荐答案

You need to add @JsonClass(generateAdapter = true) before your data class

@JsonClass(generateAdapter = true) 
data class Spot(
    var id: String = "",
    var localizedName: String? = null,
    var type: String = "",
    var location: Location? = null
)

Kotlin相关问答推荐

导入org.gradle.jvm.toolchain.internal.JavaToolchainFactory未解析引用:Java工具链工厂

在Kotlin 有更好的结合方式?

我可以在kotlin/java.util.scanner中跳过分隔符而不重复吗?

如何更改默认推断没有接收者的函数类型?

通过快捷键手动砍掉功能参数等

创建包含 3 个相同项目的列表/使用返回类型重复

Kotlin supervisorScope 即使包裹在 try catch 中也会失败

使用 Jetpack Compose 使用参数导航

MyType.()在 Kotlin 中是什么意思?

在jetpack compose中将默认方向设置为横向?

在 Kotlin 协程中切换 IO 和 UI 的正确方法是什么?

使用 Compose for Desktop Bundle 文件

Jetpack compose 可滚动表格

创建首选项屏幕时找不到androidx.preference.PreferenceScreen

零安全的好处

如何通过反射使用 Kotlin 对象

在Kotlin中不带类直接引用枚举实例

用Gradle Kotlin DSL构建源jar?

Kotlin - 是否可以在类中的 init 块之前初始化伴随对象?

如何判断数据是否插入到房间数据库中