Android Moshi 1.9.1无法序列化Kotlin类型
我有一个使用Moshi 1.8.0序列化/反序列化数据的工作代码 现在,升级到1.9.1会在尝试序列化时导致崩溃: java.lang.IllegalArgumentException:无法序列化Kotlin类型 com.xxx.Spot。Kotlin类的反射序列化 使用kotlin reflect具有未定义和意外的行为。请使用 来自moshi kotlin工件的KotlinJsonAdapter或使用来自 moshi kotlin codegen人工制品 以下是序列化程序代码:Android Moshi 1.9.1无法序列化Kotlin类型,android,kotlin,moshi,Android,Kotlin,Moshi,我有一个使用Moshi 1.8.0序列化/反序列化数据的工作代码 现在,升级到1.9.1会在尝试序列化时导致崩溃: java.lang.IllegalArgumentException:无法序列化Kotlin类型 com.xxx.Spot。Kotlin类的反射序列化 使用kotlin reflect具有未定义和意外的行为。请使用 来自moshi kotlin工件的KotlinJsonAdapter或使用来自 moshi kotlin codegen人工制品 以下是序列化程序代码: val mos
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)
我完全不知道在这里该做什么
谢谢你的帮助 您需要在数据类之前添加@JsonClass(generateAdapter=true)
@JsonClass(generateAdapter = true)
data class Spot(
var id: String = "",
var localizedName: String? = null,
var type: String = "",
var location: Location? = null
)
您可以使用
@JvmSuppressWildcards
抑制通配符
像这样
val adapter: JsonAdapter<List<@JvmSuppressWildcards T>> = moshi.adapter(dataListType)
val适配器:JsonAdapter=moshi.adapter(dataListType)
如果不想将@JsonClass注释添加到所有数据类中,另一个选项是将KotlinJsonAdapterFactory添加到Moshi构建器中
Moshi.Builder()
.addLast(KotlinJsonAdapterFactory())
.build()
这使用反射,您需要添加
com.squareup.moshi:moshi-kotlin
依赖项,如本文所述您应该添加此注释
@JsonClass(generateAdapter = true)
你的数据类是这样的
@JsonClass(generateAdapter = true)
data class Spot(
var id: String = "",
var localizedName: String? = null,
var type: String = "",
var location: Location? = null
)
然后您可以使用来反序列化json数组,如下所示:
val Spots: List<Spot>? = yourJson.deserializeList()
val点:列表?=yourJson.deserializeList()
向我们展示您正在使用的依赖项为什么需要这些依赖项?。。。并在构建中包含相应的kapt配置。这里的细节:谢谢,成功了!添加@JsonClass(generateAdapter=true)+将gradle实现从“moshi”更改为“moshi kotlin”+kapt在使用JsonClass注释并尝试反射方法(moshi kotlin gradle实现)和codegen方法moshi之后仍然抛出了“无法序列化”运行时异常。即使在做了这些更改之后,还有其他人遇到过麻烦吗?@Cody-你想序列化的类中有枚举吗?需要注意的是,你需要使用.addLast()
而不是。对于Moshi v1.12+,根据他们的github文档,添加()
,谢谢,我编辑了我的答案。
val Spots: List<Spot>? = yourJson.deserializeList()