Moshi 1.9.1无法序列化Kotlin类型 [英] Moshi 1.9.1 Cannot serialize Kotlin type

查看:1008
本文介绍了Moshi 1.9.1无法序列化Kotlin类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a working code serializing/deserializing data using Moshi 1.8.0

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

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

java.lang.IllegalArgumentException:无法序列化Kotlin类型 com.xxx.Spot.不带Kotlin类的反射性序列化 使用kotlin-reflect具有未定义和意外的行为.请用 来自moshi-kotlin工件的KotlinJsonAdapter或使用来自 moshi-kotlin-codegen工件.

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)

和相应的T类是

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

我对在这里做什么一无所知.

I'm totally clueless about what to do here.

感谢您的帮助!

推荐答案

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

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
)

这篇关于Moshi 1.9.1无法序列化Kotlin类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆