NullHypothesis
NullHypothesis

Reputation: 4516

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!

Upvotes: 1

Views: 354

Answers (2)

NullHypothesis
NullHypothesis

Reputation: 4516

So this is how you do it:

Using the DeserializeObject function:

JsonConvert.DeserializeObject(jsonstring, prop.PropertyType.GenericTypeArguments[0]);

I'm now able to say "for a given json string, cast it to this type based on whatever is the property type currently". So this way, I can create an instance of what I want and then add it. It works!

Upvotes: 0

Blindy
Blindy

Reputation: 67524

I can't do a cast with a variable right?

Even if you could, what would you type that variable as? You can only work with lowest common denominators in static typed languages, and all you know at compile time is that you have a list of objects.

Once you figure out the type, you can use Enumerable.Cast<T>() to cast it to the proper type in place, but you still need a static type to do it.

Alternatively just say you can't figure it out based on the requirements you have and just use dynamic. That's kind of its purpose (besides COM interop), to work with unknown types by simply duck typing.

Upvotes: 1

Related Questions