moshi-jsonapi icon indicating copy to clipboard operation
moshi-jsonapi copied to clipboard

Get Data from 2 different types

Open famfir18 opened this issue 5 years ago • 1 comments

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

Capture Capture1

famfir18 avatar Sep 23 '19 09:09 famfir18

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

Ant8 avatar Oct 20 '20 10:10 Ant8