Moshi 1.9.1 无法序列化 Kotlin 类型

Moshi 1.9.1 Cannot serialize Kotlin type

我有一个工作代码 serializing/deserializing 使用 Moshi 1.8.0 的数据

现在升级到 1.9.1 会在尝试序列化时导致崩溃:

java.lang.IllegalArgumentException: Cannot serialize Kotlin type com.xxx.Spot. Reflective serialization of Kotlin classes without using kotlin-reflect has undefined and unexpected behavior. Please use KotlinJsonAdapter from the moshi-kotlin artifact or use code gen from the moshi-kotlin-codegen artifact.

这是序列化程序代码:

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)

对应的Tclass为

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

我完全不知道在这里做什么。

感谢您的帮助!

您需要在数据前添加@JsonClass(generateAdapter = true) class

@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)

如果您不想到处添加 @JsonClass 注释,另一个选择是将 KotlinJsonAdapterFactory 添加到 Moshi Builder。

val moshi = Moshi.Builder()
    .addLast(KotlinJsonAdapterFactory())
    .build()

这使用反射,您需要向 com.squareup.moshi:moshi-kotlin 添加依赖项,如此处解释 https://github.com/square/moshi#kotlin

您应该添加此注释

@JsonClass(generateAdapter = true) 

你的数据class要这样

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

然后您可以使用 Moshi kotlin extensions 反序列化您的 json 数组,如下所示:

val Spots: List<Spot>? = yourJson.deserializeList()