我有一个工作代码序列化/反序列化数据使用Moshi 1.8.0
当试图序列化时,升级到1.9.1现在会导致崩溃:
java.lang.IllegalArgumentException:不能序列化Kotlin类型的com.xxx.Spot。没有使用Kotlin的kotlin类的反射序列化具有未定义和意外的行为。请使用来自moshi工件的KotlinJsonAdapter,或者使用moshi codegen工件中的代码根。
以下是序列化程序代码:
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
)我完全不知道该怎么做。
谢谢你的帮助!
发布于 2019-11-01 16:01:47
您需要在数据类之前添加@JsonClass(generateAdapter = true)
@JsonClass(generateAdapter = true)
data class Spot(
var id: String = "",
var localizedName: String? = null,
var type: String = "",
var location: Location? = null
)发布于 2020-06-06 01:18:19
如果不想在各处添加@JsonClass注释,另一个选项是将KotlinJsonAdapterFactory添加到Moshi中。
val moshi = Moshi.Builder()
.addLast(KotlinJsonAdapterFactory())
.build()这使用反射,您需要向com.squareup.moshi:moshi-kotlin添加一个依赖项,如这里所解释的,https://github.com/square/moshi#kotlin
发布于 2020-03-09 21:36:00
您可以使用@JvmSuppressWildcards来禁止使用外卡。
像这样
val adapter: JsonAdapter<List<@JvmSuppressWildcards T>> = moshi.adapter(dataListType)https://stackoverflow.com/questions/58660364
复制相似问题