Moshi 1.9.1 Cannot serialize Kotlin type

*爱你&永不变心* 提交于 2019-12-10 15:28:23

问题


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

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

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.

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)

and the corresponding T class is

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

Thanks for the help!


回答1:


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
)


来源:https://stackoverflow.com/questions/58660364/moshi-1-9-1-cannot-serialize-kotlin-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!