Using generics and reflection to do a POST, then process the JSON, then return the correct type with its data.
Problem is that I won't know in advance if the type will be a single object or a list of objects. So my generic return type needs to be either a single thing, or a list of single things. (This is .NET Core 6, so what's why the !
in some places...)
How do I handle this conundrum?
private static async Task<T> ProcessJsonResponse<TX>(HttpResponseMessage response,
string? returnModel = null)
{
var result = await response.Content.ReadAsStringAsync();
if (returnModel != null)
{
var type = Type.GetType(returnModel);
var obj = (T?)Activator.CreateInstance(type!);
var test = type!.GetMethod("FromJson");
object[] parametersArray = { result };
var tim = test!.Invoke(obj, parametersArray);
if (tim is List<T> nowwhat)
{
//can't return List<t> since the return type is T
}
return (T)tim!;
}
//<snip> other non-relevant code ...
}
Aucun commentaire:
Enregistrer un commentaire