dave317
dave317

Reputation: 774

Json deserialize unknown or generic model type

This may not be possible.

Here is working code:

HttpResponseMessage playerResponse = await client.GetAsync("2018/export?TYPE=players&DETAILS=1&SINCE=&PLAYERS=9988%2C13604&JSON=1");
if (playerResponse.IsSuccessStatusCode)
{
    var json = await playerResponse.Content.ReadAsStringAsync();
    var o = JsonConvert.DeserializeObject<MFLPlayerAPIResult>(json);
    playerList = o.PlayerData.MflPlayers.ToList();                    
}

The problem is I have lots of different models similar to MFLPlayerAPIResult like my code in the above, they all use different request strings. I am trying to build a function like this:

private async Task<Object> CreateListFromJson(Type jsonclass, string request, HttpClient client)
{
    HttpResponseMessage response = await client.GetAsync(request);
    if (response.IsSuccessStatusCode)
    {
        var json = await response.Content.ReadAsStringAsync();
        var o = JsonConvert.DeserializeObject<jsonclass>(json);
        return (o);
    }
    return (null);
}

where the Object returned would be the same model as the Type jsonclass used in the parameters, then I could use the function like this:

playerList = CreateListFromJson(MFLPlayerAPIResult, request, client).PlayerData.MflPlayers.ToList();

And use it multiple times over and over with different request strings and model types.

Is this possible?

Upvotes: 2

Views: 756

Answers (1)

johnny 5
johnny 5

Reputation: 20995

If you know the type ahead of time you can just take in a generic parameter like so:

private async Task<T> CreateListFromJson<T>(string request, HttpClient client)
    where T: class
{
    var myObj = JsonConvert.DeserializeObject<T>(item);
    //...
}

If you don't know the type until compile time you can call the deserialize at runtime by passing the type

private async Task<Object> CreateListFromJson(Type jsonclass, string request, HttpClient client)
{
    var myObj = JsonConvert.DeserializeObject(item, jsonclass);
    //...
}

Upvotes: 4

Related Questions