kamikat / moshi-jsonapi

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

How to handle generic nested data #63

Closed tylergets closed 7 years ago

tylergets commented 7 years ago

Say I have a resource, in my example a "GraphObject".

It looks like this

{
    "id": "1",
    "type": "graph-objects",
    "attributes": {
      "name": "FEV1 Over Time",
      "type": "line",
      "values": [
        {
          "id": 1,
          "x": 1.76,
          "y": "2017-05-06T14:15:56.423Z"
        }
      ],
      "labels": {
        "x": "FEV1",
        "y": "Time"
      }
    }
  }

The nested field "values" will change, right now it contains an id,x, and y value. It's possible for that values field to contain other data (Such as name and count, if it's a pie graph)

I have attempted some OOP magic, but I am getting cast exceptions because of the internal values model. Is there a way to handle this and parse values to a hash map?

Thanks!

kamikat commented 7 years ago

The easiest way is to define values as List<Map<String, Object>>.

You can also implement custom JSON adapter for objects contained by values attribute which produces different type of value based on their value. https://github.com/square/moshi#custom-type-adapters

Or you can define values as JsonBuffer which stores the data stream temporarily. And decide the adapter being used to deserialize at runtime.