Created
September 24, 2013 15:45
-
-
Save vendettamit/6686786 to your computer and use it in GitHub Desktop.
Creating a generic object via reflection and invoking a method on it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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