keledrame
keledrame

Reputation: 73

How to deserialize a JSON to generic objects and get the appropriate type based on the data structure in the JSON?

I want to get the generic data object returned by these JSON:

{
  "data": {
    "playlist": {
      "id": "37682",
      "title": "my_playlist",
      "count": 12,
      "duration": 9705,
      ...
    }
  }
}

But I can also get this:

{
  "data": {
    "album": {
      "id": "372",
      "cover": ""
      "title": "Longing",
      "duration": 7705,
      "count": 12,
      "artist": "the artist"
      ...
    }
  }
}

My generic class that supposed to get the data object returned by the server:

    public class GenericResponse<T> : IGenericResponse
    {
        [JsonProperty("data")]
        public T Data { get; set; }

        object IResponse.Data => Data;
    }

One of the object I want to deserialize to from GenericResponse<T>:

    [JsonObject("playlist")]
    public class PlaylistObject
    {
        [JsonProperty("id")]
        public string Id;

        [JsonProperty("title")]
        public string Title;

        [JsonProperty("duration")]
        public int Duration;

        [JsonProperty("count")]
        public int Count;
    }

The request and deserialization:

GenericResponse result = await myEndpoint
                    .WithOAuthBearerToken(myBearer)
                    .Request()
                    .PostAsync(content)
                    .ReceiveJson<GenericResponse<T>>();

The data sent by the server is there but the result variable is always null when I deserialize it as GenericResponse<T> where T is either a PlaylistObject or an AlbumObject

Upvotes: 0

Views: 121

Answers (1)

DavidG
DavidG

Reputation: 118937

Your class stucture isn't quite correct, you are missing a wrapper class around the playlist object, something that has a playlist property. For example:

public class PlaylistWrapper
{
    public PlaylistObject Playlist { get; set; }
}

Now you should be able to deserialise directly into GenericResponse<PlaylistWrapper>

Upvotes: 1

Related Questions