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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With