Skip to content

Deserializing json with PolymorphicJsonAdapterFactory and Retrofit #1631

Closed

Description

@niclashalvorsen

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)

My dependencies:

implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-moshi:2.9.0"
implementation "com.squareup.moshi:moshi:1.14.0"
implementation "com.squareup.moshi:moshi-kotlin:1.14.0"
implementation "com.squareup.moshi:moshi-adapters:1.14.0"

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.

What am i missing here?

Activity

  1. locked and limited conversation to collaborators on Feb 14, 2023
  2. converted this issue into a discussion #1632 on Feb 14, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions