moshi-jsonapi
moshi-jsonapi copied to clipboard
Get Data from 2 different types
How to get data from one object, but that object have 2 different types?
I have object named 'metric', but 'metric' have 2 different types
it appears you need to use abstract class and polymorphic adapter factory, like this:
@JsonApi(type = TYPE)
data class SomeType(
....
val metric: HasOne<Metric> = HasOne()
...) : Resource()
then
abstract class Metric : Resource()
and
@JsonApi(type = "gamePointMetric")
data class GamePointMetric(...) : Metric()
and finally
val adapterFactory = ResourceAdapterFactory
.builder()
.add(GamePointMetric::class.java)
.add(GameStateMetric::class.java)
.build()
...
Moshi.Builder()
.add(adapterFactory)
.add(PolymorphicJsonAdapterFactory.of(Metric::class.java, "type")
 .withSubtype(GamePointMetric::class.java, "GamePointMetric")
 .withSubtype(GameStateMetric::class.java, "GameStateMetric")
)
.build()
solution thanks to @MDikkii