List <object> List <T> using reflection

I am running a json converter and I have properties decorated with a display notation. I use reflection to use this display description to determine which object to create and how it is displayed. Below is an example ...

 [JsonMapping("location", JsonMapping.MappingType.Class)] public Model.Location Location { get; set; } 

My mapping works fine until I get into the collection ...

 [JsonMapping("images", JsonMapping.MappingType.Collection)] public IList<Image> Images { get; set; } 

The problem is that I cannot convert List to a type of property list.

 private static List<object> Map(Type t, JArray json) { List<object> result = new List<object>(); var type = t.GetGenericArguments()[0]; foreach (var j in json) { result.Add(Map(type, (JObject)j)); } return result; } 

This returns a list to me, but thinking wants me to implement IConvertable before executing the property. SetValue.

Does anyone know a better way to do this?

+6
source share
1 answer

You can create a List object of the correct type using Type.MakeGenericType :

 private static IList Map(Type t, JArray json) { var elementType = t.GetGenericArguments()[0]; // This will produce List<Image> or whatever the original element type is var listType = typeof(List<>).MakeGenericType(elementType); var result = (IList)Activator.CreateInstance(listType); foreach (var j in json) result.Add(Map(type, (JObject)j)); return result; } 
+2
source

Source: https://habr.com/ru/post/897542/


All Articles