I am trying to write a method that will take a generic object
and convert it into a type of T
. The context is, I've just made a REST API call and I have the content of the response in value
. In THIS case, I happen to know that the return type is an array of strings.
But of course, that won't always be the case.
using (var response = await client.SendAsync(request))
{
HttpContent result = response.Content;
object value = ((ObjectContent)result).Value;
List<string> list = GenericToStronglyTyped<List<string>>(value);
List<string> list2 = GenericToStronglyTyped_v2<List<string>>(value);
}
I found a similar question here that seemed positive: Cast object to T
And I tried the suggested answer as follows:
private T GenericToStronglyTyped<T>(object obj)
{
if (obj is T)
{
return (T)obj;
}
try
{
return (T)Convert.ChangeType(obj, typeof(T));
}
catch (InvalidCastException)
{
return default(T);
}
}
However, this returns null
because of:
Object must implement IConvertible.
So I came up with my own solution:
private T GenericToStronglyTyped_v2<T>(object obj)
{
try
{
string json = JsonConvert.SerializeObject(obj);
return JsonConvert.DeserializeObject<T>(json);
}
catch (InvalidCastException)
{
return default(T);
}
}
That DOES work, but it feels like a bit of a gimmick. What is the best way to go about this?
Thanks!