You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Deserializing json with PolymorphicJsonAdapterFactory and Retrofit #1631
I have read about every blog and documentation there is about Moshi's PolymorphicJsonAdapterFactory but i cannot make it work for some reason.
Retrofit API & DTO's:
interface Api {
@GET
suspend fun getPayment(): Payment
}
sealed class Payment()
data class Domestic(amount : Double) : Payment()
data class International(amount : Double): Payment()
class Unknown(): Payment()
Moshi & Retrofit setup:
val adapter = PolymorphicJsonAdapterFactory.of(Payment::class.java, "paymentType")
.withSubtype(International::class.java, "INTERNATIONAL")
.withSubtype(Domestic::class.java, "DOMESTIC")
.withDefaultValue(Unknown())
val moshi = Moshi.Builder()
.add(adapter)
.add(KotlinJsonAdapterFactory())
.build()
val retrofit = Retrofit.Builder()
.....
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build()
.create(Api::class.java)
I have tried making the super class open, sealed class and interface.
Sealed:
Caused by: java.lang.IllegalArgumentException: Cannot reflectively serialize sealed class Payment. Please register an adapter.
at com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory.create(KotlinJsonAdapter.kt:224)
Interface:
Caused by: java.lang.RuntimeException: Failed to find the generated JsonAdapter class for interface "Payment"
at com.squareup.moshi.internal.Util.generatedAdapter(Util.java:590)
Open:
Dosent crash, but i'm just getting a Payment object without a parent.
I have tried to add @JsonClass(generateAdapter = true) on the data classes (and the parent) but it makes no difference.
I have also tried older versions of Moshi, but dosent seem to work for me there either.
Activity