Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moshi 1.9.1 Cannot serialize Kotlin type

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!

like image 903
lorenzo Avatar asked Nov 01 '19 13:11

lorenzo


2 Answers

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 ) 
like image 149
Olle Ekberg Avatar answered Sep 20 '22 15:09

Olle Ekberg


The other option if you don't want to add @JsonClass annotations to all your data classes is to add KotlinJsonAdapterFactory to the Moshi Builder.

Moshi.Builder()     .addLast(KotlinJsonAdapterFactory())     .build() 

This uses reflection and you need to add a dependency to com.squareup.moshi:moshi-kotlin as explained here https://github.com/square/moshi#kotlin

like image 23
miguel Avatar answered Sep 18 '22 15:09

miguel