kamikat / moshi-jsonapi

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

Support for multiple data types within a relationship #49

Closed tmtrademarked closed 7 years ago

tmtrademarked commented 7 years ago

Let's imagine that I had a relationship which could contain multiple types of data. For instance, consider the following example:

"choices": {
       "links": {
         "self": "/api/orders/42/relationships/choices",
         "related": "/api/orders/42/choices"
       },
       "data": [
         {
           "type": "recipes",
           "id": "1"
         },
         {
           "type": "wines",
           "id": "2"
         },
         {
           "type": "recipes",
           "id": "3"
         },
         {
           "type": "wines",
           "id": "4"
         },
         {
           "type": "recipes",
           "id": "5"
         },
         {
           "type": "wines",
           "id": "6"
         }
       ]
}

If all of these were Recipes, I could represent this in Java with HasMany choices. But since they're mixed, is the only way to handle this HasMany and cast check? Or is there a more graceful way to support this use case?

kamikat commented 7 years ago

As far as I know, there is no way but to cast every Resource you get from a HasMany<Resource> instance in Java.

But you can workaround that in specific cases. For example, have Choice class extends Resource and Wine and Recipe extends Choice. Then, perform some OOP magic in Choice.