samedi 21 mars 2015

Convert from generic list to specific list using reflection

I'm doing some work with Reflection. My API receives some JSON and I'd like to convert it to a list of the type it is.


Within


public override bool TrySetMember(SetMemberBinder binder, object value)


I have a cached list of properties, and one of them is a List. I know this is true because I can see from prop.PropertyType.


I would like to convert this property to an actual list, of type Foo, but I cannot seem to do this. The best I could get is a List. value is a json array of Foo (so someone sent me JSON in an array [] as Foo).



//this works, and listOfObjects is of type List<Foo> when I go deep into the quick watch of it, but it's still a list<Object> in the end.
var listOfObjects = JsonConvert.DeserializeObject<List<Object>>(value.ToString());


I can directly cast listOfObjects as List and this works, but the problem is Foo can be any type, for example Bar is also possible. So there are infinite possible types here is what i'm saying. Is there a way I can somehow tell it to be Foo when I do a cast? I'm able to get "Foo" type from my property info? I'm always able to find the type I want to convert it to using property info, but then what? I can't do a cast with a variable right?


Thanks!






Aucun commentaire:

Enregistrer un commentaire