1
votes

I have a data feed that is returning a list that could be either of three types ( Say type A, B and C ). All of the types above share 2 properties, the rest of the properties is specific to the type. I tried using the pattern.

abstract class Parent (val type: String, val id: String)

And

data class TypeA(override val type: String ... )
data class TypeB(override val type: String ... )

I am using Retrofit and trying to deserialize the list to

List<? extends Parent>

which in Kotlin should be

List<out Parent>

However GSON is throwing a deserializing error on instantiating the parent class which is abstract.

java.lang.RuntimeException: Failed to invoke public com.XX.Parent() with no args

Any ideas how I can implement this in Kotlin?

1
I think you're missing more of the exception message?Eric Cochran
For now I wrote an explicit Adapter for my abstract class, not sure if it works.user1470618

1 Answers

0
votes

As you have Moshi tagged in your question, I'll give you a way of doing it using MOshi's PolymorphicJsonAdapterFactory. You can basically parse something into different types, depending on the value of the object's property.

First thing you'll do is declared your parent type as a sealed class and have the other types extend from it:

sealed class Parent(val type: String){
    data class TypeA(override val type: String, ... ): Parent(type) 
    data class TypeB(override val type: String, ... ): Parent(type) 
}

now you're gonna tell Moshi how to parse Parent objects. You do that registering a PolymorphicJsonAdapterFactory:

val moshi = Moshi.Builder()
      .add(PolymorphicJsonAdapterFactory.of(Parent::class.java, "type")
          .withSubtype(TypeA::class.java, "typeA")
          .withSubtype(TypeB::class.java, "typeB")
      .build()

with that, if the value of the property "type" is "typeA", it will deserialize into a TypeA instance. like wise to TypeB, if property "type" is "typeB"

You can look another example here: https://github.com/square/moshi/blob/master/adapters/src/main/java/com/squareup/moshi/adapters/PolymorphicJsonAdapterFactory.java