Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<object> To List<T> using reflection

Tags:

json

c#

I'm rolling a json converter and I have properties decorated with a mapping designation. I'm using reflection to use that mapping description to determine what kind of object to create and how it maps. Below is an example...

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

My mapping works fine until I get to a collection...

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

The problem is that I cant' convert List to the list type of the property.

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;
    }

That returns me the List, but reflection wants me to implement IConvertable before doing a property.SetValue.

Anybody know of a better way to do this?

like image 852
Burke Holland Avatar asked Sep 17 '11 19:09

Burke Holland


1 Answers

You could create 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;    
}
like image 121
Bojan Resnik Avatar answered Oct 14 '22 20:10

Bojan Resnik