kamikat / moshi-jsonapi

JSON API v1.0 Specification in Moshi.
MIT License
156 stars 35 forks source link

Get Data from 2 different types #103

Open famfir18 opened 4 years ago

famfir18 commented 4 years ago

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

Ant8 commented 3 years ago

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