C# Serialization – Can All API Responses Be Serialized into One Generic Object?

cserialization

I want to consume the Tumblr API in C#. Every request to the API returns a JSON-encoded object with the same general outline:

{
    "meta": {
        "status": 200,
        "msg": "OK"
    },
    "response": { ... }
}

meta is always the same but response is specific to each request.
I would like to have all my methods return the C# equivalent of this object:

public class TumblrEnvelope
{
    [JsonProperty("meta")]
    public Meta Meta { get; set; }

    [JsonProperty("response")]
    ???
}

public class Meta
{
    [JsonProperty("status")]
    public int Status { get; set; }

    [JsonProperty("msg")]
    public string Message { get; set; }
}

but I'm not sure if it's possible to implement the Response property in such a way that I can directly serialize every response to a TumblrLEnvelope.

return JsonConvert.DeserializeObject<TumblrEnvelope>(result);

Can this be done? If not, what would be the closest I could get to it?

Best Answer

If you are using Json.Net at least. You can mix and match Jobjects with static types as you see fit. In you case it is simply a matter of doing.

public class TumblrEnvelope
{
    [JsonProperty("meta")]
    public Meta Meta { get; set; }

    [JsonProperty("response")]
    public JObject Response { get; set; }
}

Then you can taste the response and you want to turn it into a static type you can simply do(as suggested in comments by Caleth)

switch (e.Meta.Status) 
{ 
    case 200: return e.Response.ToObject<Tumblr200Response>(); 
    case 404: return e.Response.ToObject<Tumblr404Response>();
    ...
}
Related Topic