Skip to content

Instantly share code, notes, and snippets.

@vendettamit
Created September 24, 2013 15:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vendettamit/6686786 to your computer and use it in GitHub Desktop.
Save vendettamit/6686786 to your computer and use it in GitHub Desktop.
Creating a generic object via reflection and invoking a method on it.
/// <summary>
/// The deserialize to generic list.
/// </summary>
/// <param name="jsonString">
/// The json string.
/// </param>
/// <typeparam name="TReturnType">Type of a list of type TItemType
/// </typeparam>
/// <typeparam name="TItemType">Type of generic argument to list
/// </typeparam>
/// <returns>
/// The <see cref="TReturnType"/>.
/// </returns>
public static TReturnType DeserializeList<TReturnType, TItemType>(string jsonString) where TReturnType : List<TItemType>
{
var type = typeof(TReturnType);
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
{
Errors = null;
dynamic typeGenere = type.GetGenericArguments()[0];
var array = JArray.Parse(jsonString);
var objectsList = (List<TItemType>)Activator.CreateInstance(typeof(TReturnType));
foreach (var item in array)
{
try
{
objectsList.Add(item.ToObject<TItemType>());
}
catch (Exception ex)
{
Errors = Errors ?? new List<ParseErrors>();
Errors.Add(
new ParseErrors
{
ErrorDescription = ex.Message,
OriginalJson = item.ToString(),
TargetType = typeof(TReturnType)
});
}
}
return (TReturnType)objectsList;
}
else
{
return JsonConvert.DeserializeObject<TReturnType>(jsonString);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment